text:
function [VMH_existance,rBioNet_existance,metab_rBioNet_online,rxn_rBioNet_online,metabolite_structure_rBioNet] = checkAbbrExists(list,metab_rBioNet_online,rxn_rBioNet_online,metabolite_structure_rBioNet)
% This function checks whether the abbreviations in the list exist already
% in the VMH or the most recent rBioNetDB either as reaction or metabolite
% abbr
%
% INPUT
% list                          List of abbreviations (either metabolite or reactions);
%                               Alternatively a metabolite structure can be given as input and more
%                               fields are compared
% metab_rBioNet_online
% rxn_rBioNet_online
% metabolite_structure_rBioNet
%
% OUTPUT
% VMH_existance                 Lists whether the abbreviation exists in VMH (online),
%                               as a reaction (2nd entry) or as a metabolite (3rd entry)
% rBioNet_existance             Lists whether the abbreviation exists in rBioNet (as deposited in cobra toolbox online),
%                               as a reaction (2nd entry) or as a metabolite (3rd entry)
%
%
% Ines Thiele 09/2021

% create temporary folder for the rBioNetDB
mkdir('data');

check4 = {
    'keggId'
    %     'biocyc'
    'hmdb'
    %     'cheBIId'
    %     'chembl'
    %    % 'chemspider'
    %     'drugbank'
    %     'lipidmaps'
    % %    'pubChemId'
    %     'seed'
    'inchiString'
    'inchiKey'
    };

if isstruct(list)
    metabolite_structure = list;
    clear list
    F = fieldnames(metabolite_structure);
    % get VMHId's from metabolite structure
    for i = 1 : length(F)
        % contains the VMDID's for check for uniqueness as if a list would have
        % provided only
        list{i,1} = metabolite_structure.(F{i}).VMHId;
        fieldList{i,1} = metabolite_structure.(F{i}).VMHId;
        fieldList{i,2} = F{i};
        for k = 1 : length(check4)
            if isnumeric(metabolite_structure.(F{i}).(check4{k}))
                fieldList{i,k+2} = num2str(metabolite_structure.(F{i}).(check4{k}));
                %if inchikey is incorrect
            elseif string(metabolite_structure.(F{i}).(check4{k}))=='InChI'
                fieldList{i,k+2}='NaN';
            else
                fieldList{i,k+2} = metabolite_structure.(F{i}).(check4{k});
            end
        end
    end
end

% load most recent version of rBioNetDB
if ~exist('metab_rBioNet_online','var') ||  ~exist('rxn_rBioNet_online','var')
    websave('data/MetaboliteDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/MetaboliteDatabase.txt');
    websave('data/ReactionDatabase.txt','https://raw.githubusercontent.com/opencobra/COBRA.papers/master/2021_demeter/input/ReactionDatabase.txt');
    createRBioNetDBFromVMHDB('rBioNetDBFolder','data/');
    load('data/rxn.mat');
    load('data/metab.mat');
    metab_rBioNet_online = metab;
    rxn_rBioNet_online = rxn;
else
    metab = metab_rBioNet_online;
    rxn = rxn_rBioNet_online;
end

% load extended rBioNet -- Not implemented yet
if ~exist('metabolite_structure_rBioNet','var')
    load met_strc_rBioNet;
end
F = fieldnames(metabolite_structure_rBioNet);
for i = 1 : length(F)
    FR{i,1} = metabolite_structure_rBioNet.(F{i}).VMHId;
    FR{i,2} = F{i};
    for k = 1 : length(check4)
        if isnumeric(metabolite_structure_rBioNet.(F{i}).(check4{k}))
            FR{i,k+2} = num2str(metabolite_structure_rBioNet.(F{i}).(check4{k}));
        else
            if strcmp(check4{k},'hmdb')
                % preplace old style abbr with new style
                FR{i,k+2} = convertOld2NewHMDB(metabolite_structure_rBioNet.(F{i}).(check4{k}));
            else
                FR{i,k+2} = metabolite_structure_rBioNet.(F{i}).(check4{k});
            end
        end
    end
end

% check that rxn abbr does not exist in VMH or rBioNetDB
for i = 1 : size(list,1)
    % check by abbreviation
    % VMH check using the url
    VMH{i,1} = list{i};
    url1 = ['https://www.vmh.life/_api/reactions/?abbreviation=' list{i}];
    url2 = ['https://www.vmh.life/_api/metabolites/?abbreviation=' list{i}];
    output1 = webread(url1);
    output2 = webread(url2);
    if isempty(output1.results) %% rxn abbr does not exist
        VMH{i,2} = num2str(0);
    else
        VMH{i,2} = num2str(1);
    end
    if isempty(output2.results) %% met abbr does not exist
        VMH{i,3} = num2str(0);
    else
        VMH{i,3} = num2str(1);
    end
    % check by abbreviation
    % check rBioNet
    rBioNet{i,1} =  list{i};
    if ~isempty(find(ismember(rxn(:,1),list{i})))
        rBioNet{i,2} =  num2str(1);
    else
        rBioNet{i,2} =  num2str(0);
    end
    if ~isempty(find(ismember(metab(:,1),list{i})))
        rBioNet{i,3} =  num2str(1);
    else
        rBioNet{i,3} =  num2str(0);
    end
    % check against rBioNet structure
    if ~isempty(find(ismember(FR(:,1),list{i})))
        rBioNet{i,3} =  num2str(1);
        rBioNet{i,4} =  list{i};
    end
    % check using database ID's
    % against extended rBioNet structure
    if exist('metabolite_structure','var')
        for k = 1 : length(check4)
            if ~strcmp(fieldList{i,2+k},'NaN')
                if ~isempty(find(ismember(FR(:,2+k),fieldList(i,2+k))))
                    match = find(ismember(FR(:,2+k),fieldList(i,2+k)));
                    rBioNet{i,3}  =  num2str(1);
                    rBioNet{i,4}  = FR{match,1};
                    rBioNet{i,5}  = fieldList(i,2+k);
                else
                    % if there are multiple IDs possible per entry (happens a
                    % lot for HMDB). Prioritise 1. one
                    if strcmp(check4{k},'hmdb') && contains(fieldList(i,2+k),';')
                        [tok] = split(fieldList(i,2+k),';');
                        for r = 1 : length(tok)
                            if ~isempty(find(ismember(FR(:,2+k),tok{r})))
                                match = find(ismember(FR(:,2+k),tok{r}));
                                rBioNet{i,3}  =  num2str(1);
                                rBioNet{i,4}  = FR{match,1};
                                rBioNet{i,5}  = fieldList(i,2+k);
                                % once a hit is found, the others are not
                                % recorded anymore!
                                r = length(tok) + 1;
                            end
                        end
                    end
                end
            end
        end
    end
end
VMH_existance = VMH;
rBioNet_existance = rBioNet;

if ~isempty(find(contains(VMH_existance(:,2:3),'1')))
    % abbr exist in VMH
    fprintf('At least one abbrevation exists already in the VMH.\n');
else
    fprintf('All abbreviations are new to the VMH.\n');
end
if ~isempty(find(contains(rBioNet_existance(:,3),'1')))
    % abbr exist in VMH
    fprintf('At least one abbrevation exists already in rBioNet.\n');
else
    fprintf('All  abbreviations are new to rBioNet.\n ');
end

% remove temporary folder for the rBioNetDB
%warning off;
%rmdir('data','s');

author: opencobra

repo: cobratoolbox


text:
%yuv2yuv can change the resolution and format of YUV-Files.
%	yuv2yuv('Filename_old',width_old,height_old,format_old,'Filename_new',w
%	idth_new,height_new,format_new) read one YUV-File with the
%	specified resolution and format and write it to a second YUV-File with
%	the specified resolution and format.
%
%	Filename_old --> Name of original File (e.g. 'Test_old.yuv')
%   width_old    --> width of original frame  (e.g. 352)
%   height_old   --> height of original frame (e.g. 280)
%   format_old   --> subsampling rate of original YUV-File('400','411','420','422' or '444')
%	Filename_new --> Name of new File (e.g. 'Test_new.yuv')
%   width_new    --> width of new frame  (e.g. 704)
%   height_new   --> height of new frame (e.g. 560)
%   format_new   --> subsampling rate of new YUV-File('400','411','420','422' or '444')
%example: yuv2yuv('Test_old.yuv',352,288,'420','Test_new.yuv',704,560,'400')

function yuv2yuv(File_old,width_old,height_old,format_old,File_new,width_new,height_new,format_new)

    %set factor for UV-sampling
    [fwidth_old,fheight_old] = getformatfactor(format_old);
    [fwidth_new,fheight_new] = getformatfactor(format_new);
    %get Filesize and Framenumber of original File
    filep = dir(File_old);
    fileBytes = filep.bytes; %Filesize
    clear filep
    framenumber = fileBytes/(width_old*height_old*(1+2*fheight_old*fwidth_old)); %Framenumber
    if mod(framenumber,1) ~= 0
        display('Error: wrong resolution, format or filesize');
    else
        fclose(fopen(File_new,'w')); %Init File
        h = waitbar(0,'Please wait ... ');
        %read YUV-Frames
        for cntf = 1:1:framenumber
            waitbar(cntf/framenumber,h);
            YUV     = loadFileYUV(width_old,height_old,cntf,File_old,fheight_old,fwidth_old);
            YUV_new = imresize(YUV,[height_new width_new],'bicubic');
            save_yuv(YUV_new,File_new,width_new,height_new,fheight_new,fwidth_new);
        end
        close(h);
    end

%get factor for YUV-subsampling
function [fwidth,fheight] = getformatfactor(format)
    fwidth = 0.5;
    fheight= 0.5;
    if strcmp(format,'400')
        fwidth = 0;
        fheight= 0;
    elseif strcmp(format,'411')
        fwidth = 0.25;
        fheight= 1;
    elseif strcmp(format,'420')
        fwidth = 0.5;
        fheight= 0.5;
    elseif strcmp(format,'422')
        fwidth = 0.5;
        fheight= 1;
    elseif strcmp(format,'444')
        fwidth = 1;
        fheight= 1;
    else
        display('Error: wrong format');
    end

% read YUV-data from file
function YUV = loadFileYUV(width,heigth,Frame,fileName,Teil_h,Teil_b)
    % get size of U and V
    fileId = fopen(fileName,'r');
    width_h = width*Teil_b;
    heigth_h = heigth*Teil_h;
    % compute factor for framesize
    factor = 1+(Teil_h*Teil_b)*2;
    % compute framesize
    framesize = width*heigth;

    fseek(fileId,(Frame-1)*factor*framesize, 'bof');
    % create Y-Matrix
    YMatrix = fread(fileId, width * heigth, 'uchar');
    YMatrix = int16(reshape(YMatrix,width,heigth)');
    % create U- and V- Matrix
    if Teil_h == 0
        UMatrix = 0;
        VMatrix = 0;
    else
        UMatrix = fread(fileId,width_h * heigth_h, 'uchar');
        UMatrix = int16(UMatrix);
        UMatrix = reshape(UMatrix,width_h, heigth_h).';

        VMatrix = fread(fileId,width_h * heigth_h, 'uchar');
        VMatrix = int16(VMatrix);
        VMatrix = reshape(VMatrix,width_h, heigth_h).';
    end
    % compose the YUV-matrix:
    YUV(1:heigth,1:width,1) = YMatrix;

    if Teil_h == 0
        YUV(:,:,2) = 127;
        YUV(:,:,3) = 127;
    end
    % consideration of the subsampling of U and V
    if Teil_b == 1
        UMatrix1(:,:) = UMatrix(:,:);
        VMatrix1(:,:) = VMatrix(:,:);

    elseif Teil_b == 0.5
        UMatrix1(1:heigth_h,1:width) = int16(0);
        UMatrix1(1:heigth_h,1:2:end) = UMatrix(:,1:1:end);
        UMatrix1(1:heigth_h,2:2:end) = UMatrix(:,1:1:end);

        VMatrix1(1:heigth_h,1:width) = int16(0);
        VMatrix1(1:heigth_h,1:2:end) = VMatrix(:,1:1:end);
        VMatrix1(1:heigth_h,2:2:end) = VMatrix(:,1:1:end);

    elseif Teil_b == 0.25
        UMatrix1(1:heigth_h,1:width) = int16(0);
        UMatrix1(1:heigth_h,1:4:end) = UMatrix(:,1:1:end);
        UMatrix1(1:heigth_h,2:4:end) = UMatrix(:,1:1:end);
        UMatrix1(1:heigth_h,3:4:end) = UMatrix(:,1:1:end);
        UMatrix1(1:heigth_h,4:4:end) = UMatrix(:,1:1:end);

        VMatrix1(1:heigth_h,1:width) = int16(0);
        VMatrix1(1:heigth_h,1:4:end) = VMatrix(:,1:1:end);
        VMatrix1(1:heigth_h,2:4:end) = VMatrix(:,1:1:end);
        VMatrix1(1:heigth_h,3:4:end) = VMatrix(:,1:1:end);
        VMatrix1(1:heigth_h,4:4:end) = VMatrix(:,1:1:end);
    end

    if Teil_h == 1
        YUV(:,:,2) = UMatrix1(:,:);
        YUV(:,:,3) = VMatrix1(:,:);

    elseif Teil_h == 0.5
        YUV(1:heigth,1:width,2) = int16(0);
        YUV(1:2:end,:,2) = UMatrix1(:,:);
        YUV(2:2:end,:,2) = UMatrix1(:,:);

        YUV(1:heigth,1:width,3) = int16(0);
        YUV(1:2:end,:,3) = VMatrix1(:,:);
        YUV(2:2:end,:,3) = VMatrix1(:,:);

    elseif Teil_h == 0.25
        YUV(1:heigth,1:width,2) = int16(0);
        YUV(1:4:end,:,2) = UMatrix1(:,:);
        YUV(2:4:end,:,2) = UMatrix1(:,:);
        YUV(3:4:end,:,2) = UMatrix1(:,:);
        YUV(4:4:end,:,2) = UMatrix1(:,:);

        YUV(1:heigth,1:width) = int16(0);
        YUV(1:4:end,:,3) = VMatrix1(:,:);
        YUV(2:4:end,:,3) = VMatrix1(:,:);
        YUV(3:4:end,:,3) = VMatrix1(:,:);
        YUV(4:4:end,:,3) = VMatrix1(:,:);
    end
    YUV = uint8(YUV);
    fclose(fileId);

%Save YUV-Data to File
function save_yuv(data,video_file,BreiteV,HoeheV,HoehenteilerV,BreitenteilerV)

    %get Resolution od Data
    datasize = size(data);
    datasizelength = length(datasize);

    %open File
    fid = fopen(video_file,'a');

    %subsampling of U and V
    if datasizelength == 2 | HoehenteilerV == 0
        %4:0:0
        y(1:HoeheV,1:BreiteV) = data(:,:,1);
    elseif datasizelength == 3
        y(1:HoeheV,1:BreiteV) = double(data(:,:,1));
        u(1:HoeheV,1:BreiteV) = double(data(:,:,2));
        v(1:HoeheV,1:BreiteV) = double(data(:,:,3));
        if BreitenteilerV == 1
            %4:1:1
            u2 = u;
            v2 = v;
        elseif HoehenteilerV == 0.5
            %4:2:0
            u2(1:HoeheV/2,1:BreiteV/2) = u(1:2:end,1:2:end)+u(2:2:end,1:2:end)+u(1:2:end,2:2:end)+u(2:2:end,2:2:end);
            u2                         = u2/4;
            v2(1:HoeheV/2,1:BreiteV/2) = v(1:2:end,1:2:end)+v(2:2:end,1:2:end)+v(1:2:end,2:2:end)+v(2:2:end,2:2:end);
            v2                         = v2/4;
        elseif BreitenteilerV == 0.25
            %4:1:1
            u2(1:HoeheV,1:BreiteV/4) = u(:,1:4:end)+u(:,2:4:end)+u(:,3:4:end)+u(:,4:4:end);
            u2                       = u2/4;
            v2(1:HoeheV,1:BreiteV/4) = v(:,1:4:end)+v(:,2:4:end)+v(:,3:4:end)+v(:,4:4:end);
            v2                       = v2/4;
        elseif BreitenteilerV == 0.5 & HoehenteilerV == 1
            %4:2:2
            u2(1:HoeheV,1:BreiteV/2) = u(:,1:2:end)+u(:,2:2:end);
            u2                       = u2/2;
            v2(1:HoeheV,1:BreiteV/2) = v(:,1:2:end)+v(:,2:2:end);
            v2                       = v2/2;
        end
    end

    fwrite(fid,uint8(y'),'uchar'); %writes Y-Data

    if HoehenteilerV ~= 0
        %writes U- and V-Data if no 4:0:0 format
        fwrite(fid,uint8(u2'),'uchar');
        fwrite(fid,uint8(v2'),'uchar');
    end

    fclose(fid);

author: Sable

repo: mcbench-benchmarks


text:
function dxx = FTSystemWrapper(t,x,Params,K)
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FTSystemWrapper: System Dynamics with external integrators for learning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create local copies of the parameters
[F,G,Q,R] = deal(Params.F,Params.G,Params.Q,Params.R);

[e1,e2] = ExplNoise(t);
xm = BasisPlanMono(x(1),x(2));
u = K*xm + [e1;e2];

dx = F*xm + G*u;
dphi = [BasisQuadPlantMono(x(1),x(2));2*e1*R*xm;2*e2*R*xm];
dQ = xm'*(Q+K'*R*K)*xm;

dxx=[dx;dphi;dQ]; %size 2+ 34 +1 = 37
end

author: yu-jiang

repo: radpbook

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


text:
function p2 = resample(p,Np,ksType)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% resample(p,Np,KSType) -- construct a new estimate of the KDE p by sampling
%                      Np new points; determines a bandwidth by ksize(pNew,KSType)
%                      NOTE: KStype = 'discrete' resamples points by weight &
%                            preserves original kernel size
% see also: kde, ksize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt

  if (nargin < 3) ksType = 'rot'; end;
  if (nargin < 2) Np = getNpts(p); end;
  if (strcmp(ksType,'discrete'))
    q = kde(getPoints(p),zeros(getDim(p),1),getWeights(p));
    [samplePts,ind] = sample(q,Np);
    if (size(p.bandwidth,2)>2*p.N), ks = getBW(p,ind);
    else ks = getBW(p,1); end;
    p2 = kde(samplePts,ks);
  else
    samplePts = sample(p,Np);
    p2 = kde(samplePts,ksType);
  end;

author: ShapeNet

repo: RenderForCNN


text:
%==========================================================================
%                         copywrite 2011
%           iterative-Maximum ratio combining (i-MRC) detector
%     for spatial Modulation (SM) MIMO transmission technique.
%
% This Matlab code computes the BER of the SM for the case where the
% channel coefficients are modeled as uncorrelated  Rayleigh fading channel
% M is the modulation order of M-QAM schemes.
% Mt = number of transmit antennas.
% Mr = number of receive antennas.
%                This code is written by Rajab Legnain
%==========================================================================
function simulation_of_SM_iMRC()
clear all;   clc;
mode = 1;                    % mode = 1 the channel is     normalized,
                             % mode = 2 the channel is not normalized
global M Mt hmodem bit_T
M = 16;
Mt = 4;
Mr = 4;
bit_SMsym = log2(M*Mt);      % number of bit per spatial modulation sysmbol
Nbits = bit_SMsym*1e4;       % Number of bits to be simulated.

hmodem =   modem.qammod('M',M,  'SymbolOrder', 'Gray','InputType', 'bit');
hdemodem = modem.qamdemod('M', M,'SymbolOrder','Gray','OutputType','bit');
Eac = (mean(hmodem.Constellation .* conj(hmodem.Constellation)));
SNR = 0 : 2 :24;             % signal-to-noise ratio in dB
No= (Eac)*10.^(-SNR/10);     % noise variance

L_SNR=length(SNR);
ber= zeros (L_SNR,1);
bit_R=zeros(Nbits, 1);

%%
bit_T = randi([0 1],Nbits,1);
[mod_T ante]= SpatialMod();    % Spatial Modulation
mod_T = mod_T.';

for ii=1:L_SNR
    for j = 1 : size(mod_T ,2)
        channel = sqrt(.5)*( randn(Mr,Mt,1) + 1i*randn(Mr,Mt,1));
        noise = sqrt(.5)*(randn(Mr , 1) + 1i*randn(Mr , 1))* sqrt(No(ii));
        p = diag(channel'*channel);
        switch mode
            case 1
               y = channel(:,ante(j))*(mod_T(ante(j) ,j)./sqrt(p(ante(j)))) + noise;
               z = (channel'*y)./p.^.5;
            case 2
               y = channel(:,ante(j)) * mod_T(ante(j) ,j) + noise ;
               z = (channel'*y)./p;
        end
        [~,ant_est] = max(abs(z));
        bi_ant = de2bi(ant_est - 1 ,  log2(Mt)  ,'left-msb');
        bi_mod = demodulate(hdemodem, z(ant_est,1) );
        bit_R( (j-1)*bit_SMsym+1 : (j-1)*bit_SMsym+bit_SMsym,1) = [bi_ant.' ; bi_mod];

    end
    [~,ber(ii,1)] = biterr(bit_T(:,1),bit_R(:));
end

semilogy(SNR,ber(:,1),'color',[0,0.75,0.75],'linestyle','-','LineWidth',1);
grid on;
xlabel('$$SNR$$','Interpreter','latex')
ylabel('BER','Interpreter','latex')
title('Bit Error Rate of SM using i-MRC detector')
legend([num2str(M),'-QAM'] ,  'Location','NorthEast')
end

function [signal ant_no]= SpatialMod()
global M Mt hmodem bit_T
Nt    = log2(Mt);
Nobit = log2(M);
x = reshape(bit_T,Nobit+Nt,[]);

ant_no =  bi2de([x(1:Nt,:)].' , 'left-msb') + 1;
digMod = modulate(hmodem,x(Nt+1:end,:));

signal = zeros(Mt , length(digMod));

for i = 1 : length(digMod)
    signal( ant_no(i) , i) = digMod(i);
end

signal = signal.';
end


text:
function S = stripR(A)
%------------------------------------------------------------------------------
%
% Design and implementation by:
% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/
% Last Revision: June 6, 1999.
% (c) 1999-2002 Stichting CWI, Amsterdam
%------------------------------------------------------------------------------
[n, m] = size(A);
Y = A.';
S = Y(1:(m-1),:).';
%------------------------------------------------------------------------------


text:
function test_tutorial_beamformer20120321

% MEM 10gb
% WALLTIME 02:30:00
% DEPENDENCY ft_redefinetrial ft_freqanalysis ft_volumesegment ft_prepare_singleshell ft_sourceanalysis ft_prepare_leadfield ft_sourceinterpolate ft_sourceplot ft_volumenormalise

load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/data_all.mat'));

% let's just rename the variable
dataFIC = data_all;

%% Preprocess time windows of interest

cfg = [];
cfg.toilim = [-0.5 0];
dataPre = ft_redefinetrial(cfg, dataFIC);

cfg.toilim = [0.8 1.3];
dataPost = ft_redefinetrial(cfg, dataFIC);

%% Cross-spectral density

cfg = [];
cfg.method    = 'mtmfft';
cfg.output    = 'powandcsd';
cfg.tapsmofrq = 4;
cfg.foilim    = [18 18];
freqPre = ft_freqanalysis(cfg, dataPre);

cfg = [];
cfg.method    = 'mtmfft';
cfg.output    = 'powandcsd';
cfg.tapsmofrq = 4;
cfg.foilim    = [18 18];
freqPost = ft_freqanalysis(cfg, dataPost);

%% Compute (or load) the forward model)

mri = ft_read_mri(dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/Subject01.mri'));
if ~exist(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/segmentedmri.mat'), 'file')
  % segment the anatomical MRI
  cfg = [];
  cfg.write        = 'no';
  cfg.coordsys     = 'ctf';
  [segmentedmri] = ft_volumesegment(cfg, mri);
else
  % use the segmented MRI that is available
  load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/segmentedmri.mat'));
end

%% Prepare head model
cfg = [];
% vol = ft_prepare_singleshell(cfg, segmentedmri);
cfg.method = 'singleshell';
vol = ft_prepare_headmodel(cfg, segmentedmri);

%% Prepare leadfield
cfg                 = [];
cfg.grad            = freqPre.grad;
cfg.headmodel       = vol;
cfg.reducerank      = 2;
cfg.channel         = {'MEG','-MLP31', '-MLO12'};
cfg.sourcemodel.resolution = 1;   % use a 3-D grid with a 1 cm resolution
cfg.sourcemodel.unit = 'cm';
[grid] = ft_prepare_leadfield(cfg);

%% Source analysis
cfg              = [];
cfg.frequency    = 18;
cfg.method       = 'dics';
cfg.projectnoise = 'yes';
cfg.sourcemodel         = grid;
cfg.headmodel    = vol;
cfg.lambda       = 0;

sourcePre  = ft_sourceanalysis(cfg, freqPre );
sourcePost = ft_sourceanalysis(cfg, freqPost);

%save source sourcePre sourcePost

%% Plot results
cfg            = [];
cfg.downsample = 2;
cfg.parameter  = 'avg.pow';
sourcePostInt  = ft_sourceinterpolate(cfg, sourcePost , mri);

cfg              = [];
cfg.method       = 'slice';
cfg.funparameter = 'avg.pow';
figure
ft_sourceplot(cfg,sourcePostInt);

%% Plot Condition contrast

sourceDiff = sourcePost;
sourceDiff.avg.pow = (sourcePost.avg.pow - sourcePre.avg.pow) ./ sourcePre.avg.pow;

cfg            = [];
cfg.downsample = 2;
cfg.parameter  = 'avg.pow';
sourceDiffInt  = ft_sourceinterpolate(cfg, sourceDiff , mri);

cfg = [];
cfg.method        = 'slice';
cfg.funparameter  = 'avg.pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
figure
ft_sourceplot(cfg, sourceDiffInt);

%% Orthogonal cut

cfg = [];
cfg.method        = 'ortho';
cfg.funparameter  = 'avg.pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
figure
ft_sourceplot(cfg, sourceDiffInt);

%% Template MRI

cfg = [];
cfg.coordsys      = 'ctf';
cfg.nonlinear     = 'no';
sourceDiffIntNorm = ft_volumenormalise(cfg, sourceDiffInt);

cfg = [];
cfg.method        = 'ortho';
%cfg.interactive   = 'yes';
cfg.funparameter  = 'avg.pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
figure
ft_sourceplot(cfg, sourceDiffIntNorm);

%% Project to a surface
cfg = [];
cfg.coordsys   = 'ctf';
cfg.nonlinear  = 'no';
sourceDiffIntN = ft_volumenormalise(cfg, sourceDiffInt);

cfg = [];
cfg.method         = 'surface';
cfg.funparameter   = 'avg.pow';
cfg.maskparameter  = cfg.funparameter;
cfg.funcolorlim    = [0.0 1.2];
cfg.funcolormap    = 'jet';
cfg.opacitylim     = [0.0 1.2];
cfg.opacitymap     = 'rampup';
cfg.projmethod     = 'nearest';
cfg.surffile       = 'surface_white_both.mat';
cfg.surfdownsample = 10;
figure
ft_sourceplot(cfg, sourceDiffIntN);
view ([90 0])

%% Neural Activity Index (NAI)

sourceNAI = sourcePost;
sourceNAI.avg.pow = sourcePost.avg.pow ./ sourcePost.avg.noise;

cfg = [];
cfg.downsample = 2;
cfg.parameter  = 'avg.pow';
sourceNAIInt = ft_sourceinterpolate(cfg, sourceNAI , mri);

cfg = [];
cfg.method        = 'slice';
cfg.funparameter  = 'avg.pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [4.0 6.2];
cfg.opacitylim    = [4.0 6.2];
cfg.opacitymap    = 'rampup';
figure
ft_sourceplot(cfg, sourceNAIInt);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% a multigram is a degenerate 2HHMM where the bottom level HMMs emit deterministic strings
% and the the top level abstract states are independent of each other
% cf. HSMM/test_mgram2

words = {'the', 't', 'h', 'e'};
data = 'the';
nwords = length(words);
word_len = zeros(1, nwords);
word_prob = normalise(ones(1,nwords));
word_logprob = log(word_prob);
for wi=1:nwords
  word_len(wi)=length(words{wi});
end
D = max(word_len);

alphasize = 26;
data = letter2num(data);
T = length(data);

% node numbers
W = 1; % top level state = word id
L = 2; % bottom level state = letter position within word
F = 3;
O = 4;

ss = 4;
intra = zeros(ss,ss);
intra(W,[F L O])=1;
intra(L,[O F])=1;

inter = zeros(ss,ss);
inter(W,W)=1;
inter(L,L)=1;
inter(F,[W L])=1;

% node sizes
ns = zeros(1,ss);
ns(W) = nwords;
ns(L) = D;
ns(F) = 2;
ns(O) = alphasize;

% Make the DBN
bnet = mk_dbn(intra, inter, ns, 'observed', O);
eclass = bnet.equiv_class;

% uniform start distrib over words, uniform trans mat
Wstart = normalise(ones(1,nwords));
Wtrans = mk_stochastic(ones(nwords,nwords));

% always start in state 1 for each bottom level HMM
delta1_start = zeros(1, D);
delta1_start(1) = 1;
Lstart = repmat(delta1_start, nwords, 1);
LRtrans = mk_leftright_transmat(D, 0); % 0 self loop prob
Ltrans = repmat(LRtrans, [1 1 nwords]);

% Finish in the last letter of each word
Fprob = zeros(nwords, D, 2);
Fprob(:,:,1)=1;
for i=1:nwords
  Fprob(i,length(words{i}),2)=1;
  Fprob(i,length(words{i}),1)=0;
end

% Each state uniquely emits a letter
Oprob = zeros(nwords, D, alphasize);
for i=1:nwords
  for l=1:length(words{i})
    a = double(words{i}(l))-96;
    Oprob(i,l,a)=1;
  end
end

% Define CPDs for slice
bnet.CPD{eclass(W,1)} = tabular_CPD(bnet, W, 'CPT', Wstart);
bnet.CPD{eclass(L,1)} = tabular_CPD(bnet, L, 'CPT', Lstart);
bnet.CPD{eclass(F,1)} = tabular_CPD(bnet, F, 'CPT', Fprob);
bnet.CPD{eclass(O,1)} = tabular_CPD(bnet, O, 'CPT', Oprob);

% Define CPDs for slice 2
bnet.CPD{eclass(W,2)} = hhmmQ_CPD(bnet, W+ss, 'Fbelow', F, 'startprob', Wstart,  'transprob', Wtrans);
bnet.CPD{eclass(L,2)} = hhmmQ_CPD(bnet, L+ss, 'Fself', F, 'Qps', W+ss, 'startprob', Lstart, 'transprob', Ltrans);

evidence = cell(ss,T);
evidence{W,1}=1;
sample = cell2num(sample_dbn(bnet, 'length', T, 'evidence', evidence));
str = lower(sample(4,:))

engine = jtree_dbn_inf_engine(bnet);
evidence = cell(ss,T);
evidence(O,:) = num2cell(data);
[engine, ll_dbn] = enter_evidence(engine, evidence);

gamma = zeros(nwords, T);
for t=1:T
  m = marginal_nodes(engine, [W F], t);
  gamma(:,t) = m.T(:,2);
end
gamma

xidbn = zeros(nwords, nwords);
for t=1:T-1
  m = marginal_nodes(engine, [W F W+ss], t);
  xidbn = xidbn + squeeze(m.T(:,2,:));
end

% thee
% xidbn(1,4)  = 0.9412  the->e
% (2,3)=0.0588 t->h
% (3,4)=0.0588 h-e
% (4,4)=0.0588 e-e

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function startup()

curdir = fileparts(mfilename('fullpath'));

% set to edge_boxes_path the path where the edge boxes code
% (https://github.com/pdollar/edges) is installed
edge_boxes_path = '../edges/';
if exist(edge_boxes_path,'dir') > 0
    addpath(edge_boxes_path)
else
    warning('The Edge Boxes installation directory "%s" is not valid. Please install the Edge boxes code (https://github.com/pdollar/edges) and set the path to its installation directory in the edge_boxes_path variable of the startup.m file if you want use the Edge Box proposals', edge_boxes_path)
end

edge_boxes_link_path = fullfile(curdir, 'external', 'edges');
if exist(edge_boxes_link_path, 'dir') == 0
    warning('A link to the edge box installation directory is missing from external/edges; See README.md');
end

% set to pdollar_toolbox_path the path where the Piotr's Matlab Toolbox
% (http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html) is installed
pdollar_toolbox_path = '../pdollar-toolbox/';
if exist(pdollar_toolbox_path,'dir') > 0
    addpath(genpath(pdollar_toolbox_path))
else
    warning('The installation directory "%s" to Piotrs image processing toolbox (http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html) is not valid. Please install the toolbox and set the installation directory path to the pdollar_toolbox_path variable of the startup.m file if you to want use the Edge Box proposals', pdollar_toolbox_path)
end

% set to selective_search_boxes_path the path where the Selective Search code
% (http://huppelen.nl/publications/SelectiveSearchCodeIJCV.zip) is installed
selective_search_boxes_path = '../selective_search/';
if exist(selective_search_boxes_path,'dir') > 0
    addpath(genpath(selective_search_boxes_path))
else
    warning('The installation directory "%s" to the Selective Serach code (http://huppelen.nl/publications/SelectiveSearchCodeIJCV.zip) is not valid. Please install the Selective Search code and set the installation directory path to the selective_search_boxes_path variable of the startup.m file if you want to use the Selective Search proposals', selective_search_boxes_path)
end

addpath(genpath(fullfile(curdir, 'code')));
addpath(fullfile(curdir, 'bin'));

mkdir_if_missing(fullfile(curdir, 'external'));
caffe_path = fullfile(curdir, 'external', 'caffe', 'matlab');
if exist(caffe_path, 'dir') == 0
    error('matcaffe is missing from external/caffe/matlab; See README.md');
end
addpath(genpath(caffe_path));

mkdir_if_missing(fullfile(curdir, 'models-exps'));
mkdir_if_missing(fullfile(curdir, 'feat_cache'));
mkdir_if_missing(fullfile(curdir, 'data'));
mkdir_if_missing(fullfile(curdir, 'bin'));

end

author: gidariss

repo: mrcnn-object-detection


text:
%converts frequency to mel
%>
%> @param fMel: frequency
%> @param cModel: 'Fant','Shaughnessy', or 'Umesh'
%>
%> @retval Hertz value
% ======================================================================
function [fInHz] = ToolMel2Freq(fMel, cModel)

    if (nargin < 2)
        cModel  = 'Fant';
    end

    % set function handle
    hPitchFunc  = str2func (['aca' cModel '_I']);

    fInHz       = hPitchFunc(fMel);
end

function [f] = acaFant_I(m)
    %mel         = 1000 * log2(1 + f/1000);
    f   = 1000 * (2.^(m/1000)-1);
end

function [f] = acaShaughnessy_I(m)
    %mel         = 2595 * log10(1 + f/700);
    f   = 700 * (10.^(m/2595)-1);
end

function [f] = acaUmesh_I(m)
    %mel         = f./(2.4e-4*f + 0.741);
    f   = m*.741 ./ (1 - m * 2.4e-4);
end

author: alexanderlerch

repo: ACA-Code


text:
function [r, itr, status, box_num, seg_result] = fooling_seg_net(x, seg_mask_target, seg_mask_ori, net, config)
% process to generate adversarial examples in segmentation network
% -------------------------------------------------------------

try
    eval(config);
catch
    keyboard;
end

% initilization of fooling process
r = x * 0;
itr = 0;

% intilization of fooling target
[pred_target, dr, seg_result] = forward_and_back_propogation_seg(x+r, seg_mask_target, net);
box_num(itr+1) = pred_target;

pred_target_ori = sum(sum(seg_mask_ori>0));

while (pred_target > 0.01*pred_target_ori) && itr<MAX_ITER
    itr = itr + 1;
    sprintf('iteration number %d\n', itr)

    % process of noise
    dr_temp = reshape(dr, numel(dr), 1);
    r_gain = step_length/max(abs(dr_temp));
    r = r + dr*r_gain;
    r_max = max(reshape(abs(r), numel(r), 1));
    fprintf('max value in the perturbation is %.2f\n', r_max);

    % calculate the candidate for the next interation
    [pred_target, dr, seg_result] = forward_and_back_propogation_seg(x+r, seg_mask_target, net);
    fprintf('%d pixels remained\n', pred_target);
    box_num(itr+1) = pred_target;
end

if pred_target >= 0.01*pred_target_ori
    status = 0;
else
    status = 1;
end

end

author: cihangxie

repo: DAG

save_path: github-repos/MATLAB/cihangxie-DAG


text:
function expected_scale =  spm_expected_scale(min_img_sz, boxes, spm_params)
% expected_scale =  spm_expected_scale(min_img_sz, boxes, spm_params)
%
%   min_img_sz      min(size(im, 1), size(im, 2))
%   boxes           in rows with (l, t, r, b)
%
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Shaoqing Ren
%
% This file is part of the SPP code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

area = (boxes(:, 3) - boxes(:, 1) + 1) .* (boxes(:, 4) - boxes(:, 2) + 1);

expected_scale = spm_params.sz_conv_standard * spm_params.step_standard * min_img_sz ./ sqrt(area);
%     scale_expected = standard_img_size * min_img_sz ./ sqrt(area);
expected_scale = round(expected_scale(:));

end


text:
% INVWISHIRND - Inverse Wishart Random Matrix
% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright
%
%   [IW] = invwishirnd(S,d)
%
% S = p x p symmetric, postitive definite "scale" matrix
% d = "degrees of freedom" parameter
%   = "precision" parameter
%   (d must be an integer for this routine, see INVWISHRND)
%
% IW = random matrix from the inverse Wishart distribution
%
% Note:
%   different sources use different parameterizations w.r.t. nu
%   this routine uses that of Press and Shigemasu (1989):
%   density(IW) is proportional to
%     exp[-.5*trace(S*inv(IW))] / [det(IW) ^ (d/2)].
%
%   With this density definition:
%   mean(IW) = S/(d-2p-2) when d>2p+2,
%   mode(IW) = S/d.
%
% See also: INVWISHRND, WISHRND

function [IW] = invwishirnd(S,d)
[p,p2] = size(S) ;
W = wishirnd(inv(S),d-p-1) ;
IW = inv(W) ;


text:
classdef AreaColumn < DesignVariable

    properties (Access = public)

    end

    properties (Access = private)

    end

    methods (Access = public)

        function obj = AreaColumn(cParams)
            obj.init(cParams);
            obj.type = 'AreaColumn';
            obj.createInitialValue();
        end

        function A = getColumnArea(obj)
           x = obj.value;
           N = obj.mesh.nelem;
           A = x(1:N,1);
        end

        function V = computeVolum(obj)
            N = obj.mesh.nelem;
            A = obj.getColumnArea();
            V = (1/N)*sum(A);
        end

        function gamma = getFirstEigenMode(obj)
           x = obj.value;
           N = obj.mesh.nelem;
           gamma = x(N+1);
        end

        function v = getVariablesToPlot(obj)
            v{1} = obj.value;
        end

        function norm = computeL2normIncrement(obj)
            norm = 0;
        end

    end

    methods (Access = protected)

        function init(obj,cParams)
            obj.mesh = cParams.mesh;
        end

        function createInitialValue(obj)
            N = obj.mesh.nelem;
            x0 = 1*rand(N+1,1);%ones(N+1,1);
            obj.update(x0);
        end
    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
%--------------------------------------------------------------------------
%   W = word(N, theta_tgt, window_N, lamda, position, theta_jam)
%--------------------------------------------------------------------------
%   功能：
%   正交投影加宽零陷抗干扰
%--------------------------------------------------------------------------
%   输入:
%           N                       阵元数
%           theta_tgt               波束指向 度
%           window_N                指向加窗
%           lambda                  波长
%           position                阵列坐标
%           theta_jam               干扰来向
%   输出：
%           W                       加权系数
%--------------------------------------------------------------------------
%   例子:
%   N = 64;
%   lambda = 1;                                                             %波长
%   dd = lambda/2;                                                          %阵元间距d = lambda/2
%   d = 0:dd:(N-1)*dd;                                                      %构建阵列坐标
%   W= word( 64, 0,@taylorwin, lambda, d, theta_jam);                       %生成权系数
%--------------------------------------------------------------------------
function  W = word(N, theta_tgt, window_N, lamda, position, theta_jam)
%--------------------------------------------------------------------------
%   指向角的导向矢量
%--------------------------------------------------------------------------
As = window_N(N).* ...
     exp(1j*2*pi*position*sind(theta_tgt)/lamda).';

%--------------------------------------------------------------------------
%   生成单位阵
%--------------------------------------------------------------------------
In= eye( N);
Ai = [Ai exp( 1j* 2* pi* position* sind( theta_jam(idx))/ lamda).'];

%--------------------------------------------------------------------------
%   干扰来向构造矩阵
%--------------------------------------------------------------------------
P =  In - Ai*( Ai'* Ai)^-1*Ai';                                             %干扰来向的投影矩阵的 正交子空间
W_temp=(As'*P)';
W= W_temp/sqrt( W_temp'* W_temp);                                           %归一化

repo: SP


text:
function Y = abs(X)
    % Absolute value.
    %   ABS(X) is the absolute value of the elements of X. When
    %   X is complex, ABS(X) is the complex modulus (magnitude) of
    %   the elements of X.

    % Convert inputs to SymExpression
    % X = SymExpression(X);

    % construct the operation string
    sstr = ['Abs[' X.s ']'];

    % create a new object with the evaluated string
    Y = SymExpression(sstr);
end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
classdef VideoCapture < handle
    %VIDEOCAPTURE  Class for video capturing from video files or cameras
    %
    % The class provides an API for capturing video from cameras or for
    % reading video files and image sequences.
    %
    % ## Example
    % Here is how the class can be used:
    %
    %     cap = cv.VideoCapture(0);        % open the default camera
    %     pause(3);                        % see note below
    %     if ~cap.isOpened()               % check if we succeeded
    %         error('camera failed to initialized');
    %     end
    %     for t=1:30
    %         frame = cap.read();           % get a new frame from camera
    %         imshow(frame);
    %         pause(0.1);
    %     end
    %     % the camera will be deinitialized automatically in destructor
    %     % when "cap" goes out of scope
    %     % you can also explicitly call cap.release() to close the camera
    %
    % Note: In some environments, there is a concurrency issue during camera
    % initialization. To avoid unexpected crash, pause for a few seconds after
    % the initialization of cv.VideoCapture object.
    %
    % # Video I/O with OpenCV Overview
    %
    % The OpenCV "videoio" module is a set of classes and functions to read
    % and write video or images sequence.
    %
    % Basically, the module provides the cv.VideoCapture and cv.VideoWriter
    % classes as 2-layer interface to many video I/O APIs used as backend.
    %
    % ![image](https://docs.opencv.org/3.3.1/videoio_overview.svg)
    %
    % Some backends such as (`DirectShow`) Direct Show, Video For Windows
    % (`VfW`), Microsoft Media Foundation (`MediaFoundation`), Video 4 Linux
    % (`V4L`), etc... are interfaces to the video I/O library provided by the
    % operating system.
    %
    % Some others backends like OpenNI2 for Kinect, Intel Perceptual Computing
    % SDK, GStreamer, XIMEA Camera API, etc... are interfaces to proprietary
    % drivers or to external library.
    %
    % See the list of supported backends here: cv.VideoCapture.open
    %
    % Warning: Some backends are experimental use them at your own risk.
    % Note: Each backend supports devices properties (cv.VideoCapture.set) in
    % a different way or might not support any property at all.
    %
    % ## Select the backend at runtime
    % OpenCV automatically selects and uses first available backend
    % (`API='Any'`).
    %
    % As advanced usage you can select the backend to use at runtime.
    % Currently this option is available only with cv.VideoCapture.
    %
    % For example to grab from default camera using Direct Show as backend
    %
    %     % declare a capture object
    %     cap = cv.VideoCapture(0, 'API','DirectShow')
    %
    %     % or specify the API preference with open
    %     cap.open(0, 'API','DirectShow');
    %
    % If you want to grab from a file using the Direct Show as backend:
    %
    %     % declare a capture object
    %     cap = cv.VideoCapture(filename, 'API','DirectShow')
    %
    %     % or specify the API preference with open
    %     cap.open(filename, 'API','DirectShow');
    %
    % ### Enable backends
    % Backends are available only if they have been built with your OpenCV
    % binaries.
    %
    % Check in `opencv2/cvconfig.h` to know which APIs are currently available
    % (e.g. `HAVE_MSMF, HAVE_VFW, HAVE_LIBV4L`, etc...).
    %
    % To enable/disable APIs, you have to:
    % 1. re-configure OpenCV using appropriates CMake switches
    %    (e.g. `-DWITH_MSMF=ON -DWITH_VFW=ON ... `) or checking related switch
    %    in cmake-gui
    % 2. rebuild OpenCV itself
    %
    % ### Use 3rd party drivers or cameras
    % Many industrial cameras or some video I/O devices don't provide standard
    % driver interfaces for the operating system. Thus you can't use
    % cv.VideoCapture or cv.VideoWriter with these devices.
    %
    % ## The FFmpeg library
    % OpenCV can use the [FFmpeg](http://ffmpeg.org/) library as backend to
    % record, convert and stream audio and video. FFMpeg is a complete,
    % cross-reference solution. If you enable FFmpeg while configuring OpenCV
    % than CMake will download and install the binaries in
    % `OPENCV_SOURCE_CODE/3rdparty/ffmpeg/`. To use FFMpeg at runtime, you
    % must deploy the FFMepg binaries with your application.
    %
    % Note: FFmpeg is licensed under the GNU Lesser General Public License
    % (LGPL) version 2.1 or later. See
    % `OPENCV_SOURCE_CODE/3rdparty/ffmpeg/readme.txt` and
    % http://ffmpeg.org/legal.html for details and licensing information.
    %
    % See also: cv.VideoCapture.VideoCapture, cv.VideoCapture.read,
    %  cv.VideoWriter, VideoReader, mmreader, aviread, webcam, videoinput,
    %  imaq.VideoDevice, vision.VideoFileReader
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % Current position of the video file in milliseconds or video capture
        % timestamp.
        PosMsec
        % 0-based index of the frame to be decoded/captured next.
        PosFrames
        % Relative position of the video file:
        % 0 - start of the film, 1 - end of the film.
        PosAviRatio
        % Width of the frames in the video stream.
        FrameWidth
        % Height of the frames in the video stream.
        FrameHeight
        % Frame rate.
        FPS
        % 4-character code of codec. See cv.VideoWriter.open.
        FourCC
        % Number of frames in the video file.
        FrameCount
        % Format of the frames returned by cv.VideoCapture.retrieve.
        Format
        % Backend-specific value indicating the current capture mode.
        Mode
        % Brightness of the image (only for those cameras that support it).
        Brightness
        % Contrast of the image (only for cameras).
        Contrast
        % Saturation of the image (only for cameras).
        Saturation
        % Hue of the image (only for cameras).
        Hue
        % Gain of the image (only for those cameras that support it).
        Gain
        % Exposure (only for those cameras that support it).
        Exposure
        % Boolean flags indicating whether images should be converted to RGB.
        ConvertRGB
        % Rectification flag for stereo cameras
        % (note: only supported by DC1394 v2.x backend currently)
        Rectification
    end

    methods
        function this = VideoCapture(varargin)
            %VIDEOCAPTURE  Open video file or a capturing device or a IP video stream for video capturing
            %
            %     cap = cv.VideoCapture()
            %     cap = cv.VideoCapture(index)
            %     cap = cv.VideoCapture(filename)
            %     cap = cv.VideoCapture(..., 'API',apiPreference)
            %
            % ## Output
            % * __cap__ New instance of the VideoCapture
            %
            % Accepts the same inputs and options as the cv.VideoCapture.open
            % method.
            %
            % Creates a new video capture instance. With no argument, it
            % connects to the default camera device found in the system.
            % You can specify camera devices by `index`, an integer value
            % starting from 0. You can also specify a `filename` to open a
            % video file.
            %
            % See also: cv.VideoCapture.open
            %
            this.id = VideoCapture_(0, 'new');
            if nargin > 0
                this.open(varargin{:});
            else
                this.open(0);
            end
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     cap.delete()
            %
            % The method first calls cv.VideoCapture.release to close the
            % already opened file or camera.
            %
            % See also: cv.VideoCapture.release
            %
            if isempty(this.id), return; end
            VideoCapture_(this.id, 'delete');
        end

        function successFlag = open(this, index, varargin)
            %OPEN  Open video file or a capturing device or a IP video stream for video capturing
            %
            %     successFlag = cap.open(index)
            %     successFlag = cap.open(filename)
            %     successFlag = cap.open(..., 'API',apiPreference)
            %
            % ## Input
            % * __index__ id of the video capturing device to open. To open
            %   default camera using default backend just pass 0.
            % * __filename__ it can be:
            %   * name of video file (eg. `video.avi`)
            %   * or image sequence (eg. `img_%02d.jpg`, which will read
            %     samples like `img_00.jpg`, img_01.jpg`, img_02.jpg`, ...)
            %   * or URL of video stream
            %     (eg. `protocol://host:port/script_name?script_params|auth`).
            %     Note that each video stream or IP camera feed has its own
            %     URL scheme. Please refer to the documentation of source
            %     stream to know the right URL.
            %   * or device name (for backends like V4L or gPhoto2)
            %
            % ## Output
            % * __successFlag__ bool, true if the file/camera has been
            %   successfully opened.
            %
            % ## Options
            % * __API__ preferred capture API backend to use. Can be used to
            %   enforce a specific reader implementation if multiple are
            %   available: e.g. 'FFMPEG' or 'Images' or 'DirectShow'. The list
            %   of supported API backends:
            %   * __Any__ Auto detect. This is the default.
            %   * __VfW__ Video For Windows (platform native).
            %   * __V4L__ V4L/V4L2 capturing support via libv4l.
            %   * __V4L2__ Same as V4L.
            %   * __FireWire__ IEEE 1394 drivers.
            %   * __FireWare__ Same as FireWire.
            %   * __IEEE1394__ Same as FireWire.
            %   * __DC1394__ Same as FireWire.
            %   * __CMU1394__ Same as FireWire.
            %   * __QuickTime__ QuickTime.
            %   * __Unicap__ Unicap drivers.
            %   * __DirectShow__ DirectShow (via videoInput).
            %   * __PvAPI__ PvAPI, Prosilica GigE SDK.
            %   * __OpenNI__ OpenNI (for Kinect).
            %   * __OpenNIAsus__ OpenNI (for Asus Xtion).
            %   * __Android__ Android - not used.
            %   * __XIMEA__ XIMEA Camera API.
            %   * __AVFoundation__ AVFoundation framework for iOS
            %     (OS X Lion will have the same API).
            %   * __Giganetix__ Smartek Giganetix GigEVisionSDK.
            %   * __MediaFoundation__ Microsoft Media Foundation
            %     (via videoInput).
            %   * __WinRT__ Microsoft Windows Runtime using Media
            %     Foundation.
            %   * __IntelPerC__ Intel Perceptual Computing SDK.
            %   * __OpenNI2__ OpenNI2 (for Kinect).
            %   * __OpenNI2Asus__ OpenNI2 (for Asus Xtion and Occipital
            %     Structure sensors).
            %   * __gPhoto2__ gPhoto2 connection.
            %   * __GStreamer__ GStreamer.
            %   * __FFMPEG__ Open video file or stream using the FFMPEG
            %     library.
            %   * __Images__ OpenCV Image Sequence (e.g. `img_%02d.jpg`).
            %   * __Aravis__ Aravis GigE SDK.
            %   * __MotionJPEG__ Built-in OpenCV MotionJPEG codec.
            %   * __MediaSDK__ Intel MediaSDK.
            %
            % The method first calls cv.VideoCapture.release to close the
            % already opened file or camera.
            %
            % ## Example
            % Use `API` option to enforce a specific reader implementation
            % if multiple are available like 'FFMPEG' or 'Images' or
            % 'DirectShow'. For example, to open camera 1 using the
            % "MS Media Foundation" API:
            %
            %     cap.open(1, 'API','MediaFoundation')
            %
            % ### Note
            % Backends are available only if they have been built with your
            % OpenCV binaries.
            % Check your build to know which APIs are currently available.
            % To enable/disable APIs, you have to re-configure OpenCV using
            % the appropriates CMake switches and recompile OpenCV itself.
            %
            % See also: cv.VideoCapture.VideoCapture, cv.VideoCapture.isOpened
            %
            if nargin < 1, index = 0; end
            successFlag = VideoCapture_(this.id, 'open', index, varargin{:});
        end

        function retval = isOpened(this)
            %ISOPENED  Returns true if video capturing has been initialized already
            %
            %     retval = cap.isOpened()
            %
            % ## Output
            % * __retval__ bool, return value
            %
            % If the previous call to constructor or cv.VideoCapture.open
            % succeeded, the method returns true.
            %
            % See also: cv.VideoCapture.open
            %
            retval = VideoCapture_(this.id, 'isOpened');
        end

        function release(this)
            %RELEASE  Closes video file or capturing device
            %
            %     cap.release()
            %
            % The method is automatically called by subsequent
            % cv.VideoCapture.open and by destructor.
            %
            % See also: cv.VideoCapture.open
            %
            VideoCapture_(this.id, 'release');
        end

        function frame = read(this, varargin)
            %READ  Grabs, decodes and returns the next video frame
            %
            %     frame = cap.read()
            %     frame = cap.read('OptionName',optionValue, ...)
            %
            % ## Output
            % * __frame__ output image
            %
            % ## Options
            % * __FlipChannels__ in case the output is color image, flips the
            %   color order from OpenCV's BGR to MATLAB's RGB order.
            %   default true
            %
            % The method combines cv.VideoCapture.grab and
            % cv.VideoCapture.retrieve in one call. This is the most
            % convenient method for reading video files or capturing data from
            % decode and return the just grabbed frame. If no frames has been
            % grabbed (camera has been disconnected, or there are no more
            % frames in video file), the function return an empty matrix.
            %
            % See also: cv.VideoCapture.grab, cv.VideoCapture.retrieve
            %
            frame = VideoCapture_(this.id, 'read', varargin{:});
        end

        function successFlag = grab(this)
            %GRAB  Grabs the next frame from video file or capturing device
            %
            %     successFlag = cap.grab()
            %
            % ## Output
            % * __successFlag__ bool, true (non-zero) in the case of success.
            %
            % The function grabs the next frame from video file or camera and
            % returns true (non-zero) in the case of success.
            %
            % The primary use of the function is in multi-camera environments,
            % especially when the cameras do not have hardware synchronization.
            % That is, you call cv.VideoCapture.grab for each camera and after
            % that call the slower method cv.VideoCapture.retrieve to decode
            % and get frame from each camera. This way the overhead on
            % demosaicing or motion jpeg decompression etc. is eliminated and
            % the retrieved frames from different cameras will be closer in
            % time.
            %
            % Also, when a connected camera is multi-head (for example, a
            % stereo camera or a Kinect device), the correct way of retrieving
            % data from it is to call cv.VideoCapture.grab first and then call
            % cv.VideoCapture.retrieve one or more times with different values
            % of the channel parameter `StreamIdx`.
            %
            % See also: cv.VideoCapture.read, cv.VideoCapture.retrieve
            %
            successFlag = VideoCapture_(this.id, 'grab');
        end

        function frame = retrieve(this, varargin)
            %RETRIEVE  Decodes and returns the grabbed video frame
            %
            %     frame = cap.retrieve()
            %     frame = cap.retrieve('OptionName',optionValue, ...)
            %
            % ## Output
            % * __frame__ the video frame is returned here. If no frames has
            %   been grabbed the image will be empty.
            %
            % ## Options
            % * __StreamIdx__ 0-based index (for multi-head camera). It could
            %   be a frame index or a driver specific flag. default 0
            % * __FlipChannels__ in case the output is color image, flips the
            %   color order from OpenCV's BGR to MATLAB's RGB order.
            %   default true
            %
            % The function decodes and returns the just grabbed frame. If no
            % frames has been grabbed (camera has been disconnected, or there
            % are no more frames in video file), the function returns an empty
            % matrix.
            %
            % See also: cv.VideoCapture.read, cv.VideoCapture.grab
            %
            frame = VideoCapture_(this.id, 'retrieve', varargin{:});
        end

        function value = get(this, prop)
            %GET  Returns the specified VideoCapture property
            %
            %     value = cap.get(prop)
            %
            % ## Input
            % * __prop__ Property identifier. It can be specified as a string
            %   (one of the recognized properties), or directly as its
            %   corresponding integer code.
            %
            % ## Output
            % * __value__ Value for the specified property (as a `double`).
            %   Value 0 is returned when querying a property that is not
            %   supported by the backend used by the VideoCapture instance.
            %
            % ### Note
            % Reading/writing properties involves many layers. Some unexpected
            % result might happens along this chain.
            % `VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware`
            % The returned value might be different from what really used by
            % the device or it could be encoded using device dependent rules
            % (eg. steps or percentage). Effective behaviour depends from
            % device driver and API Backend.
            %
            % ## Example
            % All the following are equivalent:
            %
            %     b = cap.Brightness
            %     b = cap.get('Brightness')
            %     b = cap.get(10)  % enum value defined in OpenCV source code
            %
            % See also: cv.VideoCapture.set
            %
            value = VideoCapture_(this.id, 'get', prop);
        end

        function set(this, prop, value)
            %SET  Sets a property in the VideoCapture
            %
            %     cap.set(prop, value)
            %
            % ## Input
            % * __prop__ Property identifier. It can be specified as a string
            %   (one of the recognized properties), or directly as its
            %   corresponding integer code.
            % * __value__ Value of the property (as a `double`).
            %
            % On failure (unsupported property by backend), the function
            % issues a warning.
            %
            % Note: Even if no warning was issued, this doesn't ensure that
            % the property value has been accepted by the capture device.
            % See note in cv.VideoCapture.get.
            %
            % See also: cv.VideoCapture.get
            %
            VideoCapture_(this.id, 'set', prop, value);
        end
    end

    %% Getters/Setters
    methods
        function value = get.PosMsec(this)
            value = VideoCapture_(this.id, 'get', 'PosMsec');
        end
        function set.PosMsec(this, value)
            VideoCapture_(this.id, 'set', 'PosMsec', value);
        end

        function value = get.PosFrames(this)
            value = VideoCapture_(this.id, 'get', 'PosFrames');
        end
        function set.PosFrames(this, value)
            VideoCapture_(this.id, 'set', 'PosFrames', value);
        end

        function value = get.PosAviRatio(this)
            value = VideoCapture_(this.id, 'get', 'PosAviRatio');
        end
        function set.PosAviRatio(this, value)
            VideoCapture_(this.id, 'set', 'PosAviRatio', value);
        end

        function value = get.FrameWidth(this)
            value = VideoCapture_(this.id, 'get', 'FrameWidth');
        end
        function set.FrameWidth(this, value)
            VideoCapture_(this.id, 'set', 'FrameWidth', value);
        end

        function value = get.FrameHeight(this)
            value = VideoCapture_(this.id, 'get', 'FrameHeight');
        end
        function set.FrameHeight(this, value)
            VideoCapture_(this.id, 'set', 'FrameHeight', value);
        end

        function value = get.FPS(this)
            value = VideoCapture_(this.id, 'get', 'FPS');
        end
        function set.FPS(this, value)
            VideoCapture_(this.id, 'set', 'FPS', value);
        end

        function value = get.FourCC(this)
            value = int32(VideoCapture_(this.id, 'get', 'FourCC'));
            %value = char(typecast(value, 'uint8'));  %TODO
        end
        function set.FourCC(this, value)
            VideoCapture_(this.id, 'set', 'FourCC', value);
        end

        function value = get.FrameCount(this)
            value = VideoCapture_(this.id, 'get', 'FrameCount');
        end
        function set.FrameCount(this, value)
            VideoCapture_(this.id, 'set', 'FrameCount', value);
        end

        function value = get.Format(this)
            value = VideoCapture_(this.id, 'get', 'Format');
        end
        function set.Format(this, value)
            VideoCapture_(this.id, 'set', 'Format', value);
        end

        function value = get.Mode(this)
            value = VideoCapture_(this.id, 'get', 'Mode');
        end
        function set.Mode(this, value)
            VideoCapture_(this.id, 'set', 'Mode', value);
        end

        function value = get.Brightness(this)
            value = VideoCapture_(this.id, 'get', 'Brightness');
        end
        function set.Brightness(this, value)
            VideoCapture_(this.id, 'set', 'Brightness', value);
        end

        function value = get.Contrast(this)
            value = VideoCapture_(this.id, 'get', 'Contrast');
        end
        function set.Contrast(this, value)
            VideoCapture_(this.id, 'set', 'Contrast', value);
        end

        function value = get.Saturation(this)
            value = VideoCapture_(this.id, 'get', 'Saturation');
        end
        function set.Saturation(this, value)
            VideoCapture_(this.id, 'set', 'Saturation', value);
        end

        function value = get.Hue(this)
            value = VideoCapture_(this.id, 'get', 'Hue');
        end
        function set.Hue(this, value)
            VideoCapture_(this.id, 'set', 'Hue', value);
        end

        function value = get.Gain(this)
            value = VideoCapture_(this.id, 'get', 'Gain');
        end
        function set.Gain(this, value)
            VideoCapture_(this.id, 'set', 'Gain', value);
        end

        function value = get.Exposure(this)
            value = VideoCapture_(this.id, 'get', 'Exposure');
        end
        function set.Exposure(this, value)
            VideoCapture_(this.id, 'set', 'Exposure', value);
        end

        function value = get.ConvertRGB(this)
            value = VideoCapture_(this.id, 'get', 'ConvertRGB');
        end
        function set.ConvertRGB(this, value)
            VideoCapture_(this.id, 'set', 'ConvertRGB', value);
        end

        function value = get.Rectification(this)
            value = VideoCapture_(this.id, 'get', 'Rectification');
        end
        function set.Rectification(this, value)
            VideoCapture_(this.id, 'set', 'Rectification', value);
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function par_estc
% transport parameter estimation with derivatives             Holzbecher January 2006

global xfit cfit T D c0 c1

% Example values for Chlorid in Marmara Sea Sediment Core
T = 3.15e11;  % [s] 10.000 years
D = 1.0e-5;  % [cm*cm/s]
c0 = 0;      % [mmol/l]
c1 = 619;    % [mmol/l]
xmax = 4000; % [cm]

% specify fitting data
xfit = [0 20 40 60 100 120 140 160 215 255 275 300 375 450 525 600 750 1050 1200 1350 1650 1950 2250 2550 2700 3000 3450 3900];
cfit = [619 597 608 615 619 615 621 571 621 618 619 625 577 612 608 612 609 590 582 582 556 494 457 489 487 444 381 371];

x = [0:xmax/400:xmax];
options = optimset('Display','iter','TolFun',1e-9);
v = fzero(@myfun,0.2e-8,options);
display (['Best fit for v = ' num2str(v)]);

h = 1./(2.*sqrt(D*T)); e = diag(eye(size(x,2)));
plot (xfit,cfit,'o',x,c0+0.5*c1*(erfc(h*(x-v*T*e'))+(exp((v/D)*x)).*erfc(h*(x+v*T*e'))),'-');
legend ('given','modelled');
xlabel ('depth [cm]'); ylabel ('chloride concentration [mmol/l]');
text(0.1*xmax,c1*0.65,['sedimentation velocity [cm/a]: ' num2str(v*3.15e7)]);
e = diag(eye(size(xfit,2)));
normc = norm(cfit-c0+0.5*c1*(erfc(h*(xfit-v*T*e'))+(exp((v/D)*xfit)).*erfc(h*(xfit+v*T*e'))));
text(0.1*xmax,c1*0.6,['norm of residuals: ' num2str(normc)]);

function f = myfun(v)
global xfit cfit T D c0 c1

e=diag(eye(size(xfit,2))); h=1./(2.*sqrt(D*T));
arg1 = h*(xfit-v*T*e'); arg2 = h*(xfit+v*T*e'); arg3 = (v/D)*xfit;

% solve advection diffusion equation for c with c(t=0)=c0 and c(x=0)=c1
c = c0 + 0.5*c1*(erfc(arg1)+(exp(arg3).*erfc(arg2)));

% compute derivative of solution due to v
cv = c1*((T*h/sqrt(pi))*(exp(-arg1.*arg1)-exp(arg3).*exp(-arg2.*arg2))+0.5*(xfit/D).*exp(arg3).*erfc(arg2));

% specify function f to vanish
f = 2*(c-cfit)*cv';


text:
classdef LvdData < matlab.mixin.SetGet
    %LvdData Summary of this class goes here
    %   Detailed explanation goes here

    properties
        script LaunchVehicleScript
        launchVehicle LaunchVehicle
        stateLog LaunchVehicleStateLog
        initStateModel InitialStateModel
        optimizer LvdOptimization
        validation LaunchVehicleDataValidation
        settings LvdSettings
        notes char
        plugins LvdPluginSet
        pluginVars LvdPluginOptimVarSet
        viewSettings LaunchVehicleViewSettings
        groundObjs LaunchVehicleGroundObjectSet
        geometry LvdGeometry
        graphAnalysis LvdGraphicalAnalysis
        sensors LvdSensorSet
        sensorTgts LvdSensorTargetSet

        celBodyData
        ksptotVer char

        userData

        id(1,1) double
    end

    properties(Dependent)
        initialState LaunchVehicleStateLogEntry
    end

    methods(Access = private)
        function obj = LvdData()
            obj.stateLog = LaunchVehicleStateLog(obj);
            obj.validation = LaunchVehicleDataValidation(obj);
            obj.settings = LvdSettings();
            obj.plugins = LvdPluginSet(obj);
            obj.pluginVars = LvdPluginOptimVarSet(obj);
            obj.viewSettings = LaunchVehicleViewSettings(obj);
            obj.groundObjs = LaunchVehicleGroundObjectSet(obj);
            obj.geometry = LvdGeometry(obj);
            obj.graphAnalysis = LvdGraphicalAnalysis(obj);
            obj.sensors = LvdSensorSet(obj);
            obj.sensorTgts = LvdSensorTargetSet(obj);

            obj.id = rand();
        end
    end

    methods
        function initialState = get.initialState(obj)
            initialState = obj.initStateModel.getInitialStateLogEntry();
        end

        function tf = usesStage(obj, stage)
            tf = obj.script.usesStage(stage);
            tf = tf || obj.optimizer.usesStage(stage);
        end

        function tf = usesEngine(obj, engine)
            tf = obj.script.usesEngine(engine);
            tf = tf || obj.optimizer.usesEngine(engine);
        end

        function tf = usesTank(obj, tank)
            tf = obj.script.usesTank(tank);
            tf = tf || obj.optimizer.usesTank(tank);
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = obj.script.usesEngineToTankConn(engineToTank);
            tf = tf || obj.optimizer.usesEngineToTankConn(engineToTank);
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = obj.script.usesStopwatch(stopwatch);
            tf = tf || obj.optimizer.constraints.usesStopwatch(stopwatch);
        end

        function tf = usesExtremum(obj, extremum)
            tf = obj.script.usesExtremum(extremum);
            tf = tf || obj.optimizer.usesExtremum(extremum);
        end

        function tf = usesTankToTankConn(obj, tankToTank)
            tf = obj.script.usesTankToTankConn(tankToTank);
        end

        function tf = usesGroundObj(obj, grdObj)
            tf = obj.optimizer.usesGroundObj(grdObj) || ...
                 obj.geometry.usesGroundObj(obj);
        end

        function tf = usesCalculusCalc(obj, calculusCalc)
            tf = obj.script.usesCalculusCalc(calculusCalc);

            tf = tf || obj.optimizer.usesCalculusCalc(calculusCalc);
        end

        function tf = usesPwrSink(obj, powerSink)
            tf = obj.script.usesPwrSink(powerSink);
%             tf = tf || obj.optimizer.usesPwrStorage(powerSink);
        end

        function tf = usesPwrSrc(obj, powerSrc)
            tf = obj.script.usesPwrSrc(powerSrc);
%             tf = tf || obj.optimizer.usesPwrStorage(powerSrc);
        end

        function tf = usesPwrStorage(obj, powerStorage)
            tf = obj.script.usesPwrStorage(powerStorage);
%             tf = tf || obj.optimizer.usesPwrStorage(powerStorage);
        end

        function tf = usesGeometricPoint(obj, point)
            tf = obj.optimizer.usesGeometricPoint(point);
            tf = tf || obj.geometry.usesGeometricPoint(point);
            tf = tf || obj.sensors.usesGeometricPoint(point);
            tf = tf || obj.sensorTgts.usesGeometricPoint(point);
        end

        function tf = usesGeometricVector(obj, vector)
            tf = obj.optimizer.usesGeometricVector(vector);
            tf = tf || obj.geometry.usesGeometricVector(vector);
            tf = tf || obj.sensors.usesGeometricVector(vector);
            tf = tf || obj.sensorTgts.usesGeometricVector(vector);
        end

        function tf = usesGeometricCoordSys(obj, coordSys)
            tf = obj.optimizer.usesGeometricCoordSys(coordSys);
            tf = tf || obj.geometry.usesGeometricCoordSys(coordSys);
            tf = tf || obj.sensors.usesGeometricCoordSys(coordSys);
            tf = tf || obj.sensorTgts.usesGeometricCoordSys(coordSys);
        end

        function tf = usesGeometricRefFrame(obj, refFrame)
            tf = obj.optimizer.usesGeometricRefFrame(refFrame);
            tf = tf || obj.geometry.usesGeometricRefFrame(refFrame);
            tf = tf || obj.graphAnalysis.usesGeometricRefFrame(refFrame);
            tf = tf || obj.sensors.usesGeometricRefFrame(refFrame);
            tf = tf || obj.sensorTgts.usesGeometricRefFrame(refFrame);
        end

        function tf = usesGeometricAngle(obj, angle)
            tf = obj.optimizer.usesGeometricAngle(angle);
            tf = tf || obj.geometry.usesGeometricAngle(angle);
            tf = tf || obj.sensors.usesGeometricAngle(angle);
            tf = tf || obj.sensorTgts.usesGeometricAngle(angle);
        end

        function tf = usesGeometricPlane(obj, plane)
            tf = obj.optimizer.usesGeometricPlane(plane);
            tf = tf || obj.geometry.usesGeometricPlane(plane);
            tf = tf || obj.sensors.usesGeometricPlane(plane);
            tf = tf || obj.sensorTgts.usesGeometricPlane(plane);
        end

        function tf = usesPlugin(obj, plugin)
            tf = obj.optimizer.usesPlugin(plugin);
        end

        function tf = usesSensor(obj, sensor)
            tf = obj.script.usesSensor(sensor);
        end

        function baseFrame = getBaseFrame(obj)
            topLevelBody = obj.celBodyData.getTopLevelBody();
            baseFrame = topLevelBody.getBodyCenteredInertialFrame();
        end

        function createContinuityConstraints(obj, evt, selEvt, refBodyInfo, useTime, timeScale, usePos, posScale, useVel, velScale, useAtt, attScale, useTankMass, tankMassScale)
            arguments
                obj(1,1) LvdData
                evt(1,1) LaunchVehicleEvent
                selEvt(1,1) LaunchVehicleEvent
                refBodyInfo = [];

                useTime(1,1) logical = true;
                timeScale(1,1) double = 1.0;

                usePos(1,1) logical = true;
                posScale(1,1) double = 1.0;

                useVel(1,1) logical = true;
                velScale(1,1) double = 1.0;

                useAtt(1,1) logical = false;
                attScale(1,1) double = 1.0;

                useTankMass(1,1) logical = false;
                tankMassScale(1,1) double = 1.0;
            end

            eventNum = evt.getEventNum();
            selEvtNum = selEvt.getEventNum();

            if(eventNum > selEvtNum)
                refEvt = evt;
                constrEvt = selEvt;
            else
                refEvt = selEvt;
                constrEvt = evt;
            end

            if(isempty(refBodyInfo))
                stateLogEntry = obj.stateLog.getLastStateLogForEvent(refEvt);
                refBodyInfo = stateLogEntry.centralBody;
            end
            frame = refBodyInfo.getBodyCenteredInertialFrame();

            cs = AbstractConstraint.empty(1,0);

            %time
            if(useTime)
                c = GenericMAConstraint('Universal Time', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(timeScale);
                cs(end+1) = c;
            end

            %position
            if(usePos)
                c = GenericMAConstraint('Position Vector (X)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(posScale);
                cs(end+1) = c;

                c = GenericMAConstraint('Position Vector (Y)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(posScale);
                cs(end+1) = c;

                c = GenericMAConstraint('Position Vector (Z)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(posScale);
                cs(end+1) = c;
            end

            %velocity
            if(useVel)
                c = GenericMAConstraint('Velocity Vector (X)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(velScale);
                cs(end+1) = c;

                c = GenericMAConstraint('Velocity Vector (Y)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(velScale);
                cs(end+1) = c;

                c = GenericMAConstraint('Velocity Vector (Z)', refEvt, 0, 0, [], [], refBodyInfo);
                c.setScaleFactor(velScale);
                cs(end+1) = c;
            end

            %attitude
            if(useAtt)
                c = RollAngleConstraint(refEvt, 0, 0);
                c.setScaleFactor(attScale);
                cs(end+1) = c;

                c = PitchAngleConstraint(refEvt, 0, 0);
                c.setScaleFactor(attScale);
                cs(end+1) = c;

                c = YawAngleConstraint(refEvt, 0, 0);
                c.setScaleFactor(attScale);
                cs(end+1) = c;
            end

            %tank masses
            if(useTankMass)
                [~,tanks] = obj.launchVehicle.getTanksListBoxStr();

                for(i=1:length(tanks))
                    c = TankMassConstraint(tanks(i), refEvt, 0, 0);
                    c.setScaleFactor(tankMassScale);
                    cs(end+1) = c; %#ok<AGROW>
                end
            end

            for(i=1:length(cs))
                c = cs(i);
                c.evalType = ConstraintEvalTypeEnum.StateComparison;
                c.stateCompType = ConstraintStateComparisonTypeEnum.Equals;
                c.stateCompEvent = constrEvt;
                c.frame = frame;

                obj.optimizer.constraints.addConstraint(c);
            end
        end
    end

    methods(Static)
        function lvdData = getEmptyLvdData()
            lvdData = LvdData();
            lvdData.ksptotVer = getKSPTOTVersionNumStr();
        end

        function lvdData = getDefaultLvdData(celBodyData)
            lvdData = LvdData();

            lvdData.celBodyData = celBodyData;

            simDriver = LaunchVehicleSimulationDriver(lvdData);

            %Set Up Initial Launch Vehicle
            lv = LaunchVehicle.createDefaultLaunchVehicle(lvdData);
            lvdData.launchVehicle = lv;

            %Set Up Initial State
            initBody = LvdData.getDefaultInitialBodyInfo(celBodyData);

            initStateModel = InitialStateModel.getDefaultInitialStateLogModelForLaunchVehicle(lvdData.launchVehicle, initBody);
            lvdData.initStateModel = initStateModel;

            %Set Up Mission Script
            script = LaunchVehicleScript(lvdData, simDriver);
            script.addEvent(LaunchVehicleEvent.getDefaultEvent(script));

            lvdData.script = script;

            %State Log
            lvdData.stateLog = LaunchVehicleStateLog(lvdData);

            %Optimization
            lvdOptim = LvdOptimization(lvdData);

            %Objective Function
%             lvdOptim.objFcn = NoOptimizationObjectiveFcn(lvdOptim, lvdData);
            lvdOptim.objFcn = CompositeObjectiveFcn(GenericObjectiveFcn.empty(1,0), ...
                                                    ObjFcnDirectionTypeEnum.Minimize, ...
                                                    ObjFcnCompositeMethodEnum.Sum, ...
                                                    lvdData.optimizer, lvdData);

            lvdData.optimizer = lvdOptim;

            %set up view profile
            lvdData.viewSettings.selViewProfile.frame = lvdData.initialState.centralBody.getBodyCenteredInertialFrame();

            %set up ground objects
            grndObj = LaunchVehicleGroundObject.getDefaultObj(celBodyData);
            lvdData.groundObjs.addGroundObj(grndObj);
            grndObj.name = 'KSC';
            grndObj.desc = "Kerbin Space Center";

            bfFrame = grndObj.centralBodyInfo.getBodyFixedFrame();

            durToNextWayPt = 3600;
            elemSet = GeographicElementSet(grndObj.initialTime + durToNextWayPt, deg2rad(-0.1025), deg2rad(285.42472), 0.06841, 0, 0, 0, bfFrame);
            wayPt = LaunchVehicleGroundObjectWayPt(elemSet, durToNextWayPt);
            grndObj.wayPts = wayPt;
        end

        function lvdData = getLvdDataFromMfmsOutputs(mfmsOutputs)
            lvdData = LvdData.getDefaultLvdData(mfmsOutputs.celBodyData);
            lvdOptim = lvdData.optimizer;

            wayPtBodies = [mfmsOutputs.wayPtBodies{:}];

            [~, colorEnums] = ColorSpecEnum.getListboxStr();

            %Xfer orbit data
            xferOrbits = mfmsOutputs.xferOrbits; %sma ecc inc raan arg tru tru2 t1 t2 gmu
            xferOrbitDurations = xferOrbits(:,9) - xferOrbits(:,8);

            %Set critical settings
            maxSimDur = 10*(max(xferOrbits(:,9)) - min(xferOrbits(:,8)));
            lvdData.settings.simMaxDur = maxSimDur;
            lvdData.settings.maxScriptPropTime = 10;

            %Set up view profile
            cBodyInfo = wayPtBodies(1).getParBodyInfo();

            viewProfile = lvdData.viewSettings.selViewProfile;
            viewProfile.name = sprintf('%s-centered Inertial Frame', cBodyInfo.name);
            viewProfile.frame = cBodyInfo.getBodyCenteredInertialFrame();
            viewProfile.bodiesToPlot = wayPtBodies;

            %Set Initial State
            departBody = wayPtBodies(1);
            frame = departBody.getBodyCenteredInertialFrame();
            time = xferOrbits(1,8);
            orbit = mfmsOutputs.eOrbit;
            kepElemSet = KeplerianElementSet(time, orbit(1), orbit(2), orbit(3), orbit(4), orbit(5), orbit(8), frame);

            lvdData.initStateModel.orbitModel = kepElemSet;

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %Setup Departure Event
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            event = lvdData.script.evts(1);
            event.name = sprintf('Departure from %s (+)', departBody.name);
            event.execActionsNode = ActionExecNodeEnum.BeforeProp;
            event.colorLineSpec.color = colorEnums(1);
            event.integratorObj = event.ode113Integrator;
            event.integratorObj.options.AbsTol = 1E-7;
            event.integratorObj.options.RelTol = 1E-7;
            event.integratorObj.options.NormControl = false;

            %%%Set up termination condition
            dur = xferOrbitDurations(1)/2;
            termCond = EventDurationTermCondition(dur); %/2 so that we can meet a patch point in the middle
            event.termCond = termCond;

            var = termCond.getNewOptVar();
            lvdOptim.vars.addVariable(var);

            var.lb = 0.50*dur;
            var.ub = 1.50*dur;
            var.useTf = true;

            %%%Set up delta-v action
            deltaV = mfmsOutputs.dVDepartVectNTW;
            deltaVAction = AddDeltaVAction(deltaV, DeltaVFrameEnum.OrbitNtw, true);
            event.addAction(deltaVAction);
            deltaVAction.event = event;

            var = AddDeltaVActionVariable(deltaVAction);
            lvdOptim.vars.addVariable(var);
            var.lb = deltaV - 0.50*abs(deltaV);
            var.ub = deltaV + 0.50*abs(deltaV);
            var.varDVx = true;
            var.varDVy = true;
            var.varDVz = true;

            %%%Generate active vars cache
            event.clearActiveOptVarsCache();
            event.hasActiveOptVars();

            %%%Set previous forward prop event
            prevFwdPropEvent = event;

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %Do gravity assist maneuvers
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            for(i=2:length(wayPtBodies)-1)
                bodyInfo = wayPtBodies(i);
                frame = bodyInfo.getBodyCenteredInertialFrame();
                time = xferOrbits(i,8);

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %Set up periapsis state event
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                eventPeri = LaunchVehicleEvent(lvdData.script);
                lvdData.script.addEvent(eventPeri);
                eventPeri.name = sprintf('%s Periapsis State', bodyInfo.name);
                eventPeri.execActionsNode = ActionExecNodeEnum.BeforeProp;
                eventPeri.plotMethod = EventPlottingMethodEnum.DoNotPlot;
                eventPeri.propDir = PropagationDirectionEnum.Forward;

                %%%Event line color
                colorI = mod(2*(i-1), length(colorEnums));
                eventPeri.colorLineSpec.color = colorEnums(colorI);

                %%%Set up termination condition
                termCond = EventDurationTermCondition(0); %/2 so that we can meet a patch point in the middle
                eventPeri.termCond = termCond;

                %%%Set up Set Kinematic State Action
                orbitIn = mfmsOutputs.orbitsIn(i-1,:);
                orbitModel = KeplerianElementSet(time, orbitIn(1), orbitIn(2), orbitIn(3), angleNegPiToPi(orbitIn(4)), angleNegPiToPi(orbitIn(5)), 0, frame);
                orbitModel = orbitModel.convertToUniversalElementSet();
                action = SetKinematicStateAction(lvdData.stateLog, orbitModel);

                action.inheritStateElems = true;
                action.inheritStateElemsFrom = InheritStateEnum.InheritFromLastState;
                eventPeri.addAction(action);
                action.event = eventPeri;
                action.generateLvComponentElements();

                %%%Set up Set Kinematic State variable
                var = SetKinematicStateActionVariable(action);
                lvdOptim.vars.addVariable(var);

                var.lb = 0.50*time;
                var.ub = 1.50*time;
                var.useTf = true;

                var.orbitVar.lb = [min(1.0001,0.75*orbitModel.c3), ...
                                   max(0.75*orbitModel.rP,bodyInfo.radius+bodyInfo.atmohgt), ...
                                   0, ...
                                   -2*pi, ...
                                   -2*pi, ...
                                   0];

                var.orbitVar.ub = [1.25*orbitModel.c3, ...
                                   1.25*orbitModel.rP, ...
                                   pi, ...
                                   2*pi, ...
                                   2*pi, ...
                                   0];

                var.orbitVar.varC3 = true;
                var.orbitVar.varRp = true;
                var.orbitVar.varInc = true;
                var.orbitVar.varRaan = true;
                var.orbitVar.varArg = true;
                var.orbitVar.varTau = false;

                %%%Generate active vars cache
                eventPeri.clearActiveOptVarsCache();
                eventPeri.hasActiveOptVars();

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %Set up event that props backwards from peri state
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                eventMinus = LaunchVehicleEvent(lvdData.script);
                lvdData.script.addEvent(eventMinus);
                eventMinus.name = sprintf('Coast from %s Periapsis (-)', bodyInfo.name);
                eventMinus.plotMethod = EventPlottingMethodEnum.PlotContinuous;
                eventMinus.propDir = PropagationDirectionEnum.Backward;
                eventMinus.integratorObj = eventMinus.ode113Integrator;
                eventMinus.integratorObj.options.AbsTol = 1E-7;
                eventMinus.integratorObj.options.RelTol = 1E-7;
                eventMinus.integratorObj.options.NormControl = false;

                %%%Event line color
                colorI = mod(2*(i-1), length(colorEnums));
                eventMinus.colorLineSpec.color = colorEnums(colorI);

                %%%Set up termination condition
                dur = xferOrbitDurations(i-1)/2;
                termCond = EventDurationTermCondition(dur); %/2 so that we can meet a patch point in the middle
                eventMinus.termCond = termCond;

                var = termCond.getNewOptVar();
                lvdOptim.vars.addVariable(var);
                var.lb = 0.50*dur;
                var.ub = 1.50*dur;
                var.useTf = true;

                %%%Create continuity constraint
                lvdData.createContinuityConstraints(eventMinus, prevFwdPropEvent, cBodyInfo, true, 1, true, 1, true, 1, false, 1, false, 1);

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %Set up periapsis state event and propagate FORWARDS
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                eventPlus = LaunchVehicleEvent(lvdData.script);
                lvdData.script.addEvent(eventPlus);
                eventPlus.name = sprintf('Coast from %s Periapsis (+)', bodyInfo.name);
                eventPlus.execActionsNode = ActionExecNodeEnum.BeforeProp;
                eventPlus.plotMethod = EventPlottingMethodEnum.SkipFirstState;
                eventPlus.propDir = PropagationDirectionEnum.Forward;
                eventPlus.integratorObj = eventPlus.ode113Integrator;
                eventPlus.integratorObj.options.AbsTol = 1E-7;
                eventPlus.integratorObj.options.RelTol = 1E-7;
                eventPlus.integratorObj.options.NormControl = false;

                %%%Event line color
                colorI = mod(2*(i-1)+1, length(colorEnums));
                eventPlus.colorLineSpec.color = colorEnums(colorI);

                %%%Set up termination condition
                dur = xferOrbitDurations(i)/2; %/2 so that we can meet a patch point in the middle
                termCond = EventDurationTermCondition(dur);
                eventPlus.termCond = termCond;

                var = termCond.getNewOptVar();
                lvdOptim.vars.addVariable(var);

                var.lb = 0.50*dur;
                var.ub = 1.50*dur;
                var.useTf = true;

                %%%Set up Set Kinematic State Action
                orbitModel = KeplerianElementSet(time, orbitIn(1), orbitIn(2), orbitIn(3), angleNegPiToPi(orbitIn(4)), angleNegPiToPi(orbitIn(5)), 0, frame);
                orbitModel = orbitModel.convertToUniversalElementSet();

                action = SetKinematicStateAction(lvdData.stateLog, orbitModel);
                eventPlus.addAction(action);
                action.event = eventPlus;

                action.inheritTime = true;
                action.inheritTimeFrom = InheritStateEnum.InheritFromSpecifiedEvent;
                action.inheritTimeFromEvent = eventPeri;

                action.inheritPosVel = true;
                action.inheritPosVelFrom = InheritStateEnum.InheritFromSpecifiedEvent;
                action.inheritPosVelFromEvent = eventPeri;

                action.inheritStateElems = true;
                action.inheritStateElemsFrom = InheritStateEnum.InheritFromSpecifiedEvent;
                action.inheritStateElemsFromEvent = eventPeri;

                action.generateLvComponentElements();

                %%%Set up delta-v action
                deltaV = mfmsOutputs.deltaVVectNTW(:,i-1);
                action = AddDeltaVAction(deltaV, DeltaVFrameEnum.OrbitNtw, true);
                eventPlus.addAction(action);
                action.event = eventPlus;

                var = AddDeltaVActionVariable(action);
                lvdOptim.vars.addVariable(var);
                var.lb = deltaV - 0.50*abs(deltaV);
                var.ub = deltaV + 0.50*abs(deltaV);
                var.varDVx = true;
                var.varDVy = false;
                var.varDVz = false;

                %%%Generate active vars cache
                eventPlus.clearActiveOptVarsCache();
                eventPlus.hasActiveOptVars();

                %%%Set previous forward prop event
                prevFwdPropEvent = eventPlus;
            end

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %Set up periapsis state for arrive body
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            arriveBodyInfo = wayPtBodies(end);
            frame = arriveBodyInfo.getBodyCenteredInertialFrame();
            time = xferOrbits(end,9);

            %Compute an inbound orbit
            vInfArriveIn = mfmsOutputs.vInfArrive;
            vInfArriveMag = norm(vInfArriveIn);

            gmu = arriveBodyInfo.gm;
            sma = -gmu / vInfArriveMag^2;
            rP = arriveBodyInfo.radius + arriveBodyInfo.atmohgt + 0.1*arriveBodyInfo.radius;
            ecc = 1 - rP/sma;

            turnAngle = 2*acos(-1/ecc);
            R = rotz(rad2deg(turnAngle));
            vInfArriveOut = R * vInfArriveIn;

            [~, ~, hHat, sHat, ~, ~, ~] = computeMultiFlyByParameters(vInfArriveIn, vInfArriveOut, gmu);
            [hSMAIn, hEccIn, hIncIn, hRAANIn, hArgIn, ~, ~, ~] = computeHyperOrbitFromMultiFlybyParams(sma, ecc, hHat, sHat, true);

            %Create event
            event = LaunchVehicleEvent(lvdData.script);
            lvdData.script.addEvent(event);
            event.name = sprintf('%s Periapsis State', arriveBodyInfo.name);
            event.execActionsNode = ActionExecNodeEnum.BeforeProp;
            event.plotMethod = EventPlottingMethodEnum.SkipFirstState;
            event.propDir = PropagationDirectionEnum.Backward;
            event.integratorObj.options.AbsTol = 1E-7;
            event.integratorObj.options.RelTol = 1E-7;
            event.integratorObj.options.NormControl = false;

            %%%Event line color
            event.colorLineSpec.color = ColorSpecEnum.Blue;

            %%%Set up termination condition
            dur = 0; %/2 so that we can meet a patch point in the middle
            termCond = EventDurationTermCondition(dur); %/2 so that we can meet a patch point in the middle
            event.termCond = termCond;

            %%%Set up Set Kinematic State Action
            orbitModel = KeplerianElementSet(time, hSMAIn, hEccIn, hIncIn, angleNegPiToPi(hRAANIn), angleNegPiToPi(hArgIn), 0, frame);
            orbitModel = orbitModel.convertToUniversalElementSet();
            action = SetKinematicStateAction(lvdData.stateLog, orbitModel);

            action.inheritStateElems = true;
            action.inheritStateElemsFrom = InheritStateEnum.InheritFromLastState;
            event.addAction(action);
            action.event = event;

            action.generateLvComponentElements();

            %%%Set up Set Kinematic State variable
            var = SetKinematicStateActionVariable(action);
            lvdOptim.vars.addVariable(var);

            var.lb = 0.50*time;
            var.ub = 1.50*time;
            var.useTf = true;

            var.orbitVar.lb = [min(1.0001,0.75*orbitModel.c3), ...
                               max(0.75*orbitModel.rP,arriveBodyInfo.radius+arriveBodyInfo.atmohgt), ...
                               0, ...
                               -2*pi, ...
                               -2*pi, ...
                               0];

            var.orbitVar.ub = [1.25*orbitModel.c3, ...
                               1.25*orbitModel.rP, ...
                               pi, ...
                               2*pi, ...
                               2*pi, ...
                               0];

            var.orbitVar.varC3 = true;
            var.orbitVar.varRp = true;
            var.orbitVar.varInc = true;
            var.orbitVar.varRaan = true;
            var.orbitVar.varArg = true;
            var.orbitVar.varTau = false;

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %Prop BACKWARDS from periapsis state for arrive body
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %Create event
            event = LaunchVehicleEvent(lvdData.script);
            lvdData.script.addEvent(event);
            event.name = sprintf('Coast from %s Arrival (-)', arriveBodyInfo.name);
            event.execActionsNode = ActionExecNodeEnum.BeforeProp;
            event.plotMethod = EventPlottingMethodEnum.SkipFirstState;
            event.propDir = PropagationDirectionEnum.Backward;
            event.integratorObj.options.AbsTol = 1E-7;
            event.integratorObj.options.RelTol = 1E-7;
            event.integratorObj.options.NormControl = false;

            %%%Event line color
            event.colorLineSpec.color = ColorSpecEnum.Blue;

            %%%Set up termination condition
            dur = xferOrbitDurations(end)/2; %/2 so that we can meet a patch point in the middle
            termCond = EventDurationTermCondition(dur); %/2 so that we can meet a patch point in the middle
            event.termCond = termCond;

            var = termCond.getNewOptVar();
            lvdOptim.vars.addVariable(var);

            var.lb = 0.50*dur;
            var.ub = 1.50*dur;
            var.useTf = true;

            %%%Create continuity constraint
            lvdData.createContinuityConstraints(event, prevFwdPropEvent, cBodyInfo, true, 1, true, 1, true, 1, false, 1, false, 1);

            %Set up objective function
            fcn = GenericMAConstraint('Total Spacecraft Mass', event, 0, 0, [], [], cBodyInfo);
            objFcn = GenericObjectiveFcn(event, cBodyInfo.getBodyCenteredInertialFrame(), fcn, 1, lvdOptim, lvdData);
            lvdOptim.objFcn.addObjFunc(objFcn);
            lvdOptim.objFcn.dirType = ObjFcnDirectionTypeEnum.Maximize;
        end

        function initBody = getDefaultInitialBodyInfo(celBodyData)
            if(isfield(celBodyData,'kerbin'))
                initBody = celBodyData.kerbin;
            elseif(isfield(celBodyData,'earth'))
                initBody = celBodyData.earth;
            else
                fields = fieldnames(celBodyData);
                initBody = celBodyData.(fields{1});
            end
        end

        function obj = loadobj(obj)
            arguments
                obj LvdData
            end

            obj.validation = LaunchVehicleDataValidation(obj);

            if(isempty(obj.stateLog))
                obj.stateLog = LaunchVehicleStateLog(obj);
            end

            if(isempty(obj.stateLog.lvdData))
                obj.stateLog.lvdData = obj;
            end

            if(isempty(obj.plugins))
                obj.plugins = LvdPluginSet(obj);
            end

            if(isempty(obj.pluginVars))
                obj.pluginVars = LvdPluginOptimVarSet(obj);
            end

            if(isempty(obj.viewSettings))
                obj.viewSettings = LaunchVehicleViewSettings(obj);

                for(i=1:length(obj.viewSettings.viewProfiles))
                    profile = obj.viewSettings.viewProfiles(i);

                    if(isempty(profile.frame))
                        originBodyInfo = obj.getDefaultInitialBodyInfo(obj.celBodyData);
                        profile.frame = originBodyInfo.getBodyCenteredInertialFrame();
                    end
                end
            end

            if(isempty(obj.groundObjs))
                obj.groundObjs = LaunchVehicleGroundObjectSet(obj);
            end

            if(isempty(obj.geometry))
                obj.geometry = LvdGeometry(obj);
            end

            if(isempty(obj.graphAnalysis))
                obj.graphAnalysis = LvdGraphicalAnalysis(obj);
            end

            if(isempty(obj.sensors))
                obj.sensors = LvdSensorSet(obj);
            end

            if(isempty(obj.sensorTgts))
                obj.sensorTgts = LvdSensorTargetSet(obj);
            end

            evts = obj.script.evts;
            for(i=1:length(evts)) %#ok<*NO4LP>
                evts(i).createUpdatedSetKinematicStateObjs();
            end

            nonSeqEvts = obj.script.nonSeqEvts.nonSeqEvts;
            for(i=1:length(nonSeqEvts))
                nonSeqEvts(i).evt.createUpdatedSetKinematicStateObjs();
            end

            if(isempty(obj.id) || obj.id == 0)
                obj.id = rand();
            end
        end

        function obj = saveobj(obj)
            obj.stateLog.clearStateLog();
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function determ = conex2_determinant ( alpha )

%*****************************************************************************80
%
%% CONEX2_DETERMINANT returns the determinant of the CONEX2 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real ALPHA, the scalar defining A.
%
%    Output, real DETERM, the determinant.
%
  determ = 1.0 / alpha;

  return
end

author: johannesgerer

repo: jburkardt-m