text:
%   CLASS File_Wizard
% =========================================================================
%
% DESCRIPTION
%   Class to check and prepare the files needed by the processing
%   (e.g. navigational files)
%
% EXAMPLE
%   settings = FTP_Server();
%
% FOR A LIST OF CONSTANTs and METHODS use doc File_Wizard
%
% REQUIRES:
%   goGPS settings;
%
% COMMENTS
%   Server structure:

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:        Andrea Gatti
%  Contributors:      Andrea Gatti, Giulio Tagliaferro
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

classdef File_Wizard < handle

    properties (SetAccess = protected, GetAccess = public)
        date_start; % first epoch of common observations (among all the obs files)
        date_stop;  % last epoch of common observations (among all the obs files)
        rm;         % resource manager
        sys_c;      % system collector
        current_resource; % current resource being processed
        vmf_res; %vfm resolution
        vmf_source; % vmf source

        nrt = false;%near real time flag % continue even if all the files have not been found
    end

    properties (SetAccess = private, GetAccess = private)
        fnp = File_Name_Processor();
        ftp_downloaders;
    end

    methods
        function this = File_Wizard()
            % Constructor
            %  SYNTAX File_Wizard(<state>)
            % Uses state for getting settings info
            % Modify state to update eph_name and clk_name
            state = Core.getState;
            this.rm = Remote_Resource_Manager(state.getRemoteSourceFile());
            this.sys_c = state.getConstellationCollector.getActiveSysChar;
        end

        function [status] = conjureResource(this, resource_name, date_start, date_stop, center_name, flag_check)
            % Conjure the desired resource giveng the desired center
            % and the times bounds
            %
            % SYNTAX:
            %   [status] = this.conjureResource(resource_name, date_start, date_stop, center_name)
            %
            % INPUT:
            %      resource_name = name of the resource (e.g. final_erp)
            %      date_start = GPS_Time start
            %      date_stop = GPS_Time stop
            %      center_name = name of the center (e.g. code)
            %
            % OUPUT:
            %     status = 1 everything has been found 0 no

            log = Core.getLogger();
            if nargin < 3
                date_start = this.date_start;
                date_stop = this.date_stop;
            else
                this.date_start = date_start;
                this.date_stop = date_stop;
            end
            state = Core.getState;
            if nargin < 5
                center_name = state.getRemoteCenter;
            end
            if nargin < 6
                flag_check = true;
            end
            this.current_resource = resource_name;
            [file_tree, latency] = this.rm.getFileStr(center_name, resource_name);
            if isempty(file_tree)
                [file_tree, latency] = this.rm.getFileStr('default', resource_name);
                if isempty(file_tree)
                    status = false;
                    return;
                end
            end
            if isempty(latency)
                latency = [-Inf +Inf];
            end
            n_h_passed = (GPS_Time.now() - date_stop)/3600;
            % check local
            if flag_check
                log.addMessage(log.indent('Checking local folders ...'));
                [status, file_tree] = this.navigateTree(file_tree, 'local_check');
                if status
                    log.addStatusOk('All files have been found locally');
                else
                    log.addWarning('Some files not found locally');
                end
            else
                [status, file_tree] = this.navigateTree(file_tree, 'no_check');
            end
            % check remote
            if  state.isAutomaticDownload && ~status && flag_check
                if latency(1)~=0 && n_h_passed  < latency(1)
                    log.addWarning(log.indent(sprintf('Not enough latency for finding all the %s orbits...', resource_name)));
                    status = false;
                else
                    log.addMessage(log.indent('Checking remote folders ...'));
                    [status, file_tree, ext] = this.navigateTree(file_tree, 'remote_check');
                    if status
                        log.addStatusOk('All files have been found remotely', 10);
                    else
                        log.addError('Some files not found remotely, starting to download what it''s available');
                        status = true;
                    end

                    if status || this.nrt
                        log.addMessage(log.indent('Downloading Resources ...'));
                        [status, ~] = this.navigateTree(file_tree, 'download');
                        if not(status)
                            log.addWarning('Not all file have been found or uncompressed');
                        end
                    end
                end
            end
            this.sys_c = state.getConstellationCollector.getActiveSysChar; % set sys_c again from constellation collector
        end

        function idx = getServerIdx(this, address , port, user, passwd)
            % Get idx of server int the FTP_downlader if not present open
            % the connection and append a FTP_downloder object
            %
            % SYNTAX:
            %   idx = this.getServerIdx(address, port)
            if nargin < 3
                port = 21;
            end
            idx = 0;
            for i = 1 : length(this.ftp_downloaders)
                if strcmp(this.ftp_downloaders{i}.getAddress , address)
                    idx = i;
                    return
                end
            end
            if idx == 0
                this.ftp_downloaders{end+1} = FTP_Downloader(address, port, [], [], [], user, passwd);
                idx = length(this.ftp_downloaders);
            end
        end

        function [status, file_tree, ext] = navigateTree(this, file_tree, mode)
            % Navigate into the logical file tree (see Remote_resource_manager.getFileStr) and perform operations
            %
            % SYNTAX:
            %      [status, file_tree] = this.navigateTree(file_tree, mode)
            % INPUT:
            %     file_tree: structure containing the file tree and the
            %     logical operators
            %     mode: 'local_check' , 'remote_check' , 'download'
            log = Core.getLogger();
            status = false;
            ext = '';
            vmf_res = this.vmf_res;
            vmf_source = upper(this.vmf_source);
            state = Core.getState;
            if iscell(file_tree) % if is a leaf
                if strcmp(file_tree{1}, 'null') || file_tree{2}
                    status = true;
                    if strcmp(mode, 'download') && ~strcmp(file_tree{1},'null') && file_tree{3} ~=0
                        loc_n = file_tree{3};
                        f_struct = this.rm.getFileLoc(file_tree{1});
                        f_name = f_struct.filename;
                        f_path = [f_struct.(['loc' sprintf('%03d',loc_n)]) f_name];
                        step_s = min(3*3600, this.fnp.getStepSec(f_path)); %supposing a polynomial of degree 12 and SP3 orbit data every 15 min (at worst)
                        dsa = this.date_start.getCopy();
                        dso = this.date_stop.getCopy();
                        if not(abs(this.fnp.getStepSec(f_path) -7862400) < 1e-3)
                            dsa.addIntSeconds(-step_s);
                            dso.addIntSeconds(+step_s);
                        end
                        [file_name_lst, date_list] = this.fnp.dateKeyRepBatch(f_path, dsa, dso,'0','0','0',vmf_res,vmf_source);
                        file_name_lst = flipud(file_name_lst);

                        f_status_lst = file_tree{4};
                        f_ext_lst = file_tree{5};

                        if ~isempty(file_name_lst) && (any(strfind(file_name_lst{1}, 'garner')) || any(strfind(file_name_lst{1}, 'cddis')))
                            % It seems like aria does not work with graner FTP, it does not download all the file requested, some fails
                            aria_err_code = true; % switch to matlab FTP download
                        else
                            [f_status_lst, aria_err_code] = Core_Utils.aria2cDownloadUncompress(file_name_lst, f_ext_lst, f_status_lst, date_list);
                        end
                        for i = 1 : length(file_name_lst)
                            if isempty(f_status_lst) || ~f_status_lst(i) && aria_err_code % do this only if aria fails
                                file_name = file_name_lst{i};
                                server = regexp(file_name,'(?<=\?{)\w*(?=})','match','once'); % search for ?{server_name} in paths
                                file_name = strrep(file_name,['?{' server '}'],'');
                                [s_ip, port, user, passwd] = this.rm.getServerIp(server);
                                out_dir = state.getFileDir(file_name);
                                out_dir =  this.fnp.dateKeyRep(out_dir, date_list.getEpoch(date_list.length - i + 1),'0',vmf_res,vmf_source);
                                if ~(exist(out_dir, 'file') == 7)
                                    mkdir(out_dir);
                                end
                                %out_dir = out_dir{1};
                                if instr(port,'21')
                                    idx = this.getServerIdx(s_ip, port, user, passwd);
                                    if ~this.nrt
                                        %status = status && this.ftp_downloaders{idx}.downloadUncompress(file_name, out_dir);
                                        status = this.ftp_downloaders{idx}.downloadUncompress(file_name, out_dir) && status;
                                    else
                                        status = this.ftp_downloaders{idx}.downloadUncompress(file_name, out_dir) && status;
                                    end
                                    f_status_lst(i) = status;
                                elseif instr(port,'80')
                                    if ~this.nrt
                                        %status = status && Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd);
                                        status = Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd) && status;
                                    else
                                        status = Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd) && status;
                                    end
                                    f_status_lst(i) = status;
                                elseif  instr(port,'443')
                                    if ~this.nrt
                                        %status = status && Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd,true);
                                        status = Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd,true) && status;
                                    else
                                        status = Core_Utils.downloadHttpTxtResUncompress([s_ip file_name], out_dir, user, passwd,true) && status;
                                    end
                                    f_status_lst(i) = status;
                                end
                            else
                                status = all(f_status_lst(1 : i));
                            end
                        end
                        if ~aria_err_code && ~status
                            Core.getLogger.addWarning(sprintf('Aria was able to download only %d of %d files', sum(f_status_lst), numel(f_status_lst)));
                        end
                    end
                elseif ~strcmp(mode, 'download')
                    f_struct = this.rm.getFileLoc(file_tree{1});
                    if isempty(f_struct.filename)
                        log.addError(sprintf('File resource "%s" not found: remote_resource.ini seems to be corrupted', file_tree{1}));
                    else
                        f_name = f_struct.filename;
                        state.setFile(f_name, this.current_resource);
                        if strcmp(mode, 'local_check') || strcmp(mode, 'no_check')
                            f_path = this.fnp.checkPath([state.getFileDir(f_name) filesep f_name]);
                            step_s = min(3*3600, this.fnp.getStepSec(f_path)); %supposing a polynomial of degree 12 and SP3 orbit data every 15 min (at worst)
                            dsa = this.date_start.getCopy();
                            dso = this.date_stop.getCopy();
                            if not(abs(this.fnp.getStepSec(f_path) -7862400) < 1e-3)
                                dsa.addIntSeconds(-step_s);
                                dso.addIntSeconds(+step_s);
                            end
                            file_name_lst = flipud(this.fnp.dateKeyRepBatch(f_path, dsa, dso,'0','0','0',vmf_res,vmf_source));
                            %file_name_lst = this.fnp.dateKeyRepBatch(f_path, dsa, dso,'0','0','0',vmf_res,vmf_source);
                            % Manage ultra rapid resources (they overlap 18 hours in the future
                            try
                                is_ultra = strcmpi(f_name(1:3), 'IGU') || strcmpi(file_tree{1}(end-4:end), 'ultra');
                            catch
                                is_ultra = false;
                            end
                            if is_ultra
                                dso_ur = dso.getCopy; dso_ur.addIntSeconds(-18*3600);
                                file_name_lst_ur = flipud(this.fnp.dateKeyRepBatch(f_path, dsa, dso_ur,'0','0','0',vmf_res,vmf_source));
                                %file_name_lst_ur = this.fnp.dateKeyRepBatch(f_path, dsa, dso_ur,'0','0','0',vmf_res,vmf_source);
                            else
                                file_name_lst_ur = file_name_lst;
                            end
                            status = true;
                            f_status_lst = false(length(file_name_lst),1); % file list to be saved in tree with flag of downloaded or not
                            if strcmp(mode, 'local_check')
                                for i = 1 : length(file_name_lst)
                                    file_info = dir(file_name_lst{i});
                                    if isempty(file_info)
                                        f_status = false;
                                    else
                                        % if the file is empty delete it
                                        if (file_info.bytes == 0)
                                            f_status = false;
                                            log.addError(sprintf('"%s" file is empty => deleting it...', [file_name_lst{i}]));
                                            delete(file_name_lst{i});
                                        else
                                            f_status = true;
                                        end
                                    end

                                    %if numel(file_name_lst) - (3 + numel(file_name_lst_ur)) < 0
                                    f_status_lst(i) = f_status;
                                    status = status && f_status;
                                    if f_status
                                        log.addStatusOk(sprintf('%s ready',this.fnp.getFileName(file_name_lst{i})), 20); % logging on 10 (default is 9, if ok do not show this)
                                    else
                                        log.addWarning(sprintf('%s have not been found locally', file_name_lst{i}));
                                    end
                                    %else
                                    %     log.addWarning(sprintf('%s have not been found locally, but it is not essential', this.fnp.getFileName(file_name_lst{i})));
                                    %end
                                end
                            end
                            if status
                                file_tree{3} = 0;
                            end
                            file_tree{4} = f_status_lst;
                        elseif strcmp(mode, 'remote_check')

                            old_server = struct('name', '', 's_ip', '', 'port', '');
                            for i = 1 : f_struct.loc_number
                                f_path = [f_struct.(['loc' sprintf('%03d',i)]) f_name];
                                step_s = min(3*3600, this.fnp.getStepSec(f_path)); %supposing a polynomial of degree 12 and SP3 orbit data every 15 min (at worst)
                                dsa = this.date_start.getCopy();
                                dso = this.date_stop.getCopy();
                                if not(abs(this.fnp.getStepSec(f_path) -7862400) < 1e-3)
                                    dsa.addIntSeconds(-step_s);
                                    dso.addIntSeconds(+step_s);
                                end
                                file_name_lst = flipud(this.fnp.dateKeyRepBatch(f_path, dsa, dso,'0','0','0',vmf_res,vmf_source));
                                %file_name_lst = this.fnp.dateKeyRepBatch(f_path, dsa, dso,'0','0','0',vmf_res,vmf_source);
                                % Manage ultra rapid resources (they overlap 18 hours in the future
                                try
                                    is_ultra = strcmpi(f_name(1:3), 'IGU') || strcmpi(file_tree{1}(end-4:end), 'ultra');
                                catch
                                    is_ultra = false;
                                end
                                if is_ultra
                                    dso_ur = dso.getCopy; dso_ur.addIntSeconds(-18*3600);
                                    file_name_lst_ur = flipud(this.fnp.dateKeyRepBatch(f_path, dsa, dso_ur,'0','0','0',vmf_res,vmf_source));
                                    %file_name_lst_ur = this.fnp.dateKeyRepBatch(f_path, dsa, dso_ur,'0','0','0',vmf_res,vmf_source);
                                else
                                    file_name_lst_ur = file_name_lst;
                                end
                                status = true;
                                f_status_lst = file_tree{4};
                                f_ext_lst = cell(numel(f_status_lst),1);
                                for j = 1 : length(file_name_lst)
                                    if ~f_status_lst(j)
                                        file_name = file_name_lst{j};
                                        [server] = regexp(file_name,'(?<=\?{)\w*(?=})','match'); % search for ?{server_name} in paths
                                        if isempty(server)
                                            log.addWarning(sprintf('No server is configured to download "%s"\nCheck remote_resources.ini', file_name));
                                            status = false;
                                            file_tree{4}(file_tree{4}(:) == 0) = -1;
                                        else
                                            server = server{1};
                                            file_name = strrep(file_name,['?{' server '}'],'');

                                            if strcmp(server, old_server.name)
                                                s_ip = old_server.s_ip;
                                                port = old_server.port;
                                            else
                                                [s_ip, port, user, passwd] = this.rm.getServerIp(server);
                                                old_server = struct('name', server, 's_ip', s_ip, 'port', port);
                                            end

                                            if instr(port,'21')
                                                idx = this.getServerIdx(s_ip, port, user, passwd);
                                                [stat, ext] = this.ftp_downloaders{idx}.check(file_name);
                                            elseif instr(port,'443')
                                                [stat, ext] = Core_Utils.checkHttpTxtRes(['https://' s_ip file_name]);
                                            else
                                                [stat, ext] = Core_Utils.checkHttpTxtRes([s_ip file_name]);
                                            end
                                            if ~this.nrt
                                                status = status && stat;
                                            else
                                                status = stat;
                                            end
                                            if not(stat)
                                                file_tree{4}(j) = -1;
                                            end
                                            f_ext_lst{j} = ext;
                                            if stat
                                                log.addStatusOk(sprintf('%s found (on remote server %s)', this.fnp.getFileName(file_name), server), 20);
                                            else
                                                if instr(port,'21')
                                                    log.addWarning(sprintf('"ftp://%s:%s%s" have not been found remotely', s_ip, port, file_name));
                                                else
                                                    log.addWarning(sprintf('"http://%s:%s%s" have not been found remotely', s_ip, port, file_name));
                                                end
                                                if numel(file_name_lst) - (3 + numel(file_name_lst_ur)) < 0
                                                    if ~this.nrt
                                                        break
                                                    end
                                                else
                                                    log.addWarning('File not found but precedent files cover the requested interval');
                                                    status = true;
                                                end
                                            end
                                        end

                                    end
                                end
                                status = any(file_tree{4} == 0);
                                file_tree{5} = f_ext_lst;
                                if status
                                    file_tree{3} = i;
                                end
                            end
                        end
                    end
                end
                file_tree{2} = status;
            else % is if a branch go deeper into the branches / leafs
                b_name = fieldnames(file_tree);
                b_name = b_name{1};
                or_flag = strcmp(b_name, 'or');
                and_flag = strcmp(b_name, 'and');
                if or_flag
                    status = false;
                elseif and_flag
                    status = true;
                end
                branch = fieldnames(file_tree.(b_name));
                for i = 1 :length(branch)
                    [status_b, file_tree_b, ext] = this.navigateTree(file_tree.(b_name).(branch{i}), mode);
                    if or_flag
                        status  = status || status_b;
                        if status
                            file_tree.(b_name).(branch{i}) = file_tree_b;
                            if ~this.nrt
                                break
                            end
                        end
                    elseif and_flag
                        status  = status && status_b;
                    end
                    file_tree.(b_name).(branch{i}) = file_tree_b;
                end

            end
        end

        function conjureFiles(this, date_start, date_stop, center_name)
            % Get all the files needed for processing
            %
            % SYNTAX:
            %     this.conjureFiles(date_start, date_stop, center_name)
            dsa = date_start.getCopy();
            dso = date_stop.getCopy();
            if (GPS_Time.now() - dso) < (24*3600)
                this.nrt = true;
            end
            state = Core.getState;
            if nargin < 4
               center_name = state.getRemoteCenter();
            end
            % check if selected center os compatible with selected
            % constellation
            centers = this.rm.getData('ORBIT_CENTER','available');
            is_ok = false;
            for i = 1 : length(centers)
                if ~is_ok
                    split = strsplit(centers{i},'@');
                    %centername = split{2};
                    %centername = strsplit(centerconst,'_');
                    %centername = centername{1};
                    sys_c = split{1};
                    if length(intersect(this.sys_c,sys_c)) == length(this.sys_c)
                        if strcmp(split{2}, center_name)
                            is_ok = true;
                            this.setCurCenter(center_name, Core.getState.getPreferredOrbit());
                        end
                    end
                end
            end

            if ~strcmp(center_name, 'none')
                state.setNoResources(false);
            end

            if ~is_ok
                if strcmp(center_name, 'none')
                    state.setNoResources(true);
                    Core.getLogger.addWarning('Resource center have not been selected, orbits will not be computed!!!');
                else
                    Core.getLogger.addError(['Selected center: ' center_name ' not compatible with selected constellations: ' this.sys_c]);
                    error('Ending execution: missing valid orbits')
                end
            end

            % Prepare all the files needed for processing

            if ~state.isNoResources()
                state.updateNavFileName();
                this.conjureNavFiles(dsa, dso);
                if state.isAutomaticDownload()
                    this.conjureBiasFiles(dsa, dso);
                    this.conjureCRXFiles(dsa, dso);
                end
                if state.needIonoMap() || state.isIonoKlobuchar()
                    this.conjureIonoFiles(dsa, dso, state.isIonoKlobuchar());
                    if false
                        this.conjureResource('hoic', dsa, dso);
                    end
                end
                if state.isAtmLoading()
                    this.conjureAtmLoadFiles(dsa, dso);
                end
                if state.isVMF()
                    this.conjureVmfFiles(dsa, dso);
                end
            end
        end

        function err_code = conjureAtmLoadFiles(this, date_start, date_stop)
            Core.getLogger.addMarkedMessage('Checking Athmospheric loading files');
            status = this.conjureResource('atm_load',date_start, date_stop);

            if status
                Core.getLogger.addStatusOk('Atmospheric loading files are present ^_^');
                err_code = 0;
            else
                Core.getLogger.addWarning('Not all atmospheric files founds, Atmospheric loading will not be applyied');
                err_code = 1;
            end

        end

        function setPreferredVMF(this, version, resolution, source)
            % Set the current VMF to download
            %
            % Available options (validity is not checked):
            %   VERSION  RESOLUTION  SOURCE
            %    '1'       '2.5x2'    'op'  (operational)
            %    '1'       '2.5x2'    'fc'  (forecast)
            %    '3'         '5x5'    'op'  (operational)
            %    '3'         '5x5'    'ei'  (ERA-Interim)
            %    '3'         '5x5'    'fc'  (forecast)
            %    '3'         '1x1'    'op'  (operational)
            %    '3'         '1x1'    'ei'  (ERA-Interim)
            %    '3'         '1x1'    'fc'  (forecast)
            %
            % SYNTAX
            %   this.setPreferredVMF(version, resolution, source)

            state = Core.getState;
            if version == '1'
                % resolution = '2.5x2';
                state.setMappingFunction(state.MF_VMF1);
                state.setPreferredVMFRes(2);
            else
                if resolution(1) == '5'
                    state.setPreferredVMFRes(3);
                    state.setMappingFunction(state.MF_VMF3_5);
                else
                    state.setPreferredVMFRes(1);
                    state.setMappingFunction(state.MF_VMF3_1);
                end
            end

            switch source(1)
                case 'o'
                    state.setPreferredVMFSource(1);
                case 'e'
                    state.setPreferredVMFSource(2);
                case 'f'
                    state.setPreferredVMFSource(3);
            end
        end

        function err_code = conjureVmfFiles(this, date_start, date_stop)
            log = Core.getLogger;
            log.addMarkedMessage('Checking VMF files');
            err_code = 1;
            date_stop = date_stop.getCopy();
            % date_stop.addSeconds(6*3600);
            % list_res = {'1x1','2.5x2','5x5'};
            list_source = {'op','ei','fc'};
            state = Core.getState;
            % list_preferred_res = list_res(state.getPreferredVMFRes());
            list_preferred_source = list_source(state.getPreferredVMFSource());
            state = Core.getCurrentSettings();
            res = [];
            if state.mapping_function == 2
                vers = '1';
                res = '2.5x2';
            elseif state.mapping_function == 4
                vers = '3';
                res = '1x1';
            elseif state.mapping_function == 5
                vers = '3';
                res = '5x5';
            end
            if not(isempty(res))
                for j = 1 : length(list_preferred_source)
                    this.vmf_res = res;
                    this.vmf_source = list_preferred_source{j};
                    state.vmf_res = res;
                    state.vmf_source = list_preferred_source{j};
                    status = this.conjureResource(['vmf' vers '_' res '_' list_preferred_source{j}], date_start, date_stop);
                    if status
                        switch list_preferred_source{j}
                            case {'op'}
                                log.addStatusOk('Operational atmospheric loading files are present ^_^');
                            case {'ei'}
                                log.addStatusOk('ERA-interim atmospheric loading files are present ^_^');
                            case {'fc'}
                                log.addStatusOk('Forecast atmospheric loading files are present ^_^');
                        end
                        break
                    end
                end

                if status
                    err_code = 0;
                    log.addStatusOk('Vienna Mapping Function files are present ^_^');
                else
                    log.addWarning('Not all vmf files founds');
                end
            end

        end

        function err_code = conjureBiasFiles(this, date_start, date_stop)
            % Download of BIAS files
            %
            % SYNTAX:
            %   this.conjureBiasFiles(gps_week, gps_time);
            %
            % INPUT:
            %   date_start = starting GPS_Time
            %   date_stop = ending GPS_Time
            %
            % OUTPUT:
            state = Core.getState();
            bias_center = state.getRemoteBiasCenter();
            status = this.conjureResource('bias', date_start, date_stop, bias_center);
            err_code = ~status;
        end

        function err_code = conjureNavFiles(this, date_start, date_stop)
            % Wrapper of conjureResources for navigational files
            %
            % SYNTAX:
            %   this.conjureNavFiles(date_start, date_stop)
            %
            log = Core.getLogger;
            log.addMarkedMessage('Checking ephemerides / clocks / ERPs');
            list_preferred = Core.getState.getPreferredEph();
            err_code = ones(1, length(list_preferred));
            status = '';
            % Reset current state info
            state = Core.getState;
            state.eph_name = '';
            state.clk_name = '';
            state.erp_name = '';
            for i = 1 : length(list_preferred)
                status = this.conjureResource(list_preferred{i}, date_start, date_stop);
                err_code(i) = ~status;
                if status || (this.nrt && (strcmp(list_preferred{i},'ultra') || strcmp(list_preferred{i},'broadcast')))
                    break
                end
            end
            if status
                switch list_preferred{i}
                    case {'final'}
                        log.addStatusOk('Final orbits files are present ^_^');
                    case {'rapid'}
                        log.addStatusOk('Rapid orbits files are present ^_^');
                    case {'ultra'}
                        log.addStatusOk('Ultra orbits files are present ^_^');
                    case {'real-time'}
                        log.addStatusOk('Real-time orbits files are present ^_^');
                    case {'broadcast'}
                        log.addStatusOk('Broadcast files are present ^_^');
                end
                log.addStatusOk('Ephemerides files are present ^_^')
            else
                if ~this.nrt
                    log.addError('Not all ephemerides files have been found program might misbehave');
                else
                    log.addError('Not all ephemerides files have been found');
                end
            end
        end

        function err_code = conjureIonoFiles(this, date_start, date_stop, flag_brdc)
            % Wrapper of conjureResources for iono files
            %
            % SYNTAX:
            %   this.conjureIonoFiles(date_start, date_stop)
            %
            log = Core.getLogger;
            err_code = 1;
            if nargin == 4 && flag_brdc
                log.addMarkedMessage('Checking broadcast ionospheric resources files');
            else
                log.addMarkedMessage('Checking ionospheric resources files');
            end
            state = Core.getState;
            list_preferred = state.preferred_iono;
            iono_center = state.getRemoteIonoCenter();
            status = true;
            for i = 1 : length(list_preferred)
                if strcmp(list_preferred{i}, 'broadcast')
                    status = this.conjureResource(['iono_' list_preferred{i}], date_start, date_stop, iono_center);
                else
                    status = this.conjureResource(['iono_' list_preferred{i}], date_start, date_stop, iono_center);
                    if flag_brdc
                        status = this.conjureResource('iono_broadcast', date_start, date_stop, iono_center);
                    end
                end
                if status
                    switch list_preferred{i}
                        case {'final'}
                            log.addStatusOk('Final ionospheric maps files are present ^_^');
                        case {'rapid'}
                            log.addStatusOk('Rapid ionospheric maps files are present ^_^');
                        case {'predicted1'}
                            log.addStatusOk('One day ahead predicted ionospheric maps files are present ^_^');
                        case {'predicted2'}
                            log.addStatusOk('Two day ahead predicted ionospheric maps files are present ^_^');
                        case {'broadcast'}
                            log.addStatusOk('Broadcast ionospheric parameters files are present');
                    end
                    break
                end
            end
            if (state.iono_model == 2) && (state.iono_management == 3 || state.flag_apr_iono)
                status = this.conjureResource('iono_broadcast', date_start, date_stop, iono_center);
            end
            if status
                err_code = 0;
                if isempty(list_preferred)
                    log.addStatusOk('No iono files requested, nothing to do!')
                else
                    log.addStatusOk('Ionosphere resource files are present ^_^')
                end
            else
                log.addWarning('Not all iono files found program might misbehave')
            end
        end

        function err_code = conjureCRXFiles(this, date_start, date_stop)
            % SYNTAX:
            %   this.conjureCRXFiles(gps_week, gps_time);
            %
            % INPUT:
            %   date_start = starting GPS_Time
            %   date_stop = ending GPS_Time
            %
            % OUTPUT:
            %
            % DESCRIPTION:
            %   Download of .CRX files from the AIUB FTP server.

            err_code = 0;
            log = Core.getLogger;
            log.addMarkedMessage('Checking CRX (Satellite problems file)');
            date_start = date_start.getCopy();
            date_stop = date_stop.getCopy();
            gps_week = double([date_start.getGpsWeek; date_stop.getGpsWeek ]);
            %gps_time = [date_start.getGpsTime; date_stop.getGpsTime ];

            % Pointer to the global settings:
            state = Core.getCurrentSettings();

            %AIUB FTP server IP address
            % aiub_ip = '130.92.9.78'; % ftp.aiub.unibe.ch
            aiub_ip = 'ftp.aiub.unibe.ch';

            %download directory
            down_dir = state.crx_dir;

            %convert GPS time to time-of-week
            [~, start_sow] = date_start.getGpsWeek;
            [~, stop_sow] = date_stop.getGpsWeek;
            gps_tow = [start_sow; stop_sow];

            % starting time
            date_f = gps2date(gps_week(1), gps_tow(1));

            % ending time
            date_l = gps2date(gps_week(end), gps_tow(end));

            % Check / create output folder
            if not(exist(down_dir, 'dir'))
                mkdir(down_dir);
            end

            year  = date_f(1) : 1 : date_l(1);
            file_crx = cell(length(year),1);

            for y = 1 : length(year)

                %target directory
                s = '/BSWUSER52/GEN';

                %target file
                s2 = ['SAT_' num2str(year(y),'%04d') '.CRX'];

                % read the last modification of the CRX
                d = dir([down_dir, '/', s2]);
                t = GPS_Time(d.datenum);

                % If there's no CRX or the CRX is older than the day of the processing and it has not been downloaded in the last day
                % do not do
                if isempty(d) || ((t < date_stop.addSeconds(10*86400)) && (GPS_Time.now - t > 43200))

                    % connect to the CRX server
                    try
                        ftp_server = ftp(aiub_ip, 'anonymous', 'info@gogps-project.org');
                    catch ex
                        log.addMessage(log.indent(sprintf(['FTP connection to the AIUB server (ftp://' aiub_ip '). Please wait...'])));
                        log.addError('Connection failed.');
                        return
                    end
                    cd(ftp_server, '/');
                    cd(ftp_server, s);

                    log.addMessage(log.indent(sprintf(['FTP connection to the AIUB server (ftp://' aiub_ip '). Please wait...'])));
                    %if not(exist([down_dir, '/', s2]) == 2)
                    try
                        move_success = false;
                        if exist(fullfile(down_dir, s2), 'file') == 2
                            [move_success, message] = movefile(fullfile(down_dir, s2), fullfile(down_dir, [s2 '.old']), 'f');
                            if ~move_success
                                log.addError(message);
                            end
                        end
                        try % ARIA2C download
                            clear file_name_lst f_ext_lst;
                            file_lst{1} = ['ftp://' aiub_ip s '/' s2];
                            f_ext_lst{1} = '';
                            f_status_lst = false;
                            f_status_lst = Core_Utils.aria2cDownloadUncompress(file_lst, f_ext_lst, f_status_lst, [], down_dir);
                        catch ex
                            % fprintf(ex.message)
                            mget(ftp_server,s2,down_dir);
                            f_status_lst = true;
                        end
                        if ~f_status_lst
                            throw(MException('Verify CRX download', 'download error'));
                        end
                    catch ex
                        log.addWarning(sprintf('CRX file have not been updated due to connection problems: %s', ex.message))
                        if exist(fullfile(down_dir, [s2, '.old']), 'file') == 2
                            if move_success
                                [move_success, message] = movefile(fullfile(down_dir, [s2 '.old']), fullfile(down_dir, s2));
                                if ~move_success
                                    err_code = 2;
                                    log.addError(message);
                                    try
                                        close(ftp_server);
                                    catch
                                    end
                                    return
                                end
                            end
                        else
                            err_code = 1;
                        end
                    end
                    log.addMessage(log.indent(sprintf(['Downloaded CRX file: ' s2 '\n'])));
                end

                % cell array with the paths to the downloaded files
                file_crx{y} = [down_dir, '/', s2];
            end

            try
                close(ftp_server);
            catch
            end
            log.addStatusOk('CRX files are present ^_^')
        end

        function err_code = conjureIGSATXFile(this)
            % SYNTAX:
            %   this.conjureIGSATXFile();
            %
            % OUTPUT:
            %   Save the latest ATX file from IGS
            %
            % DESCRIPTION:
            %   Download of .ATX files from the IGS FTP server.

            err_code = 0;
            log = Core.getLogger;
            log.addMarkedMessage('Update ATX (IGS antex file)');

            % Pointer to the global settings:
            state = Core.getCurrentSettings();

            % IGS http address
            igs_ip = 'files.igs.org';

            %download directory
            down_dir = state.atx_dir;

            % Check / create output folder
            if not(exist(down_dir, 'dir'))
                mkdir(down_dir);
            end
            % target directory
            rem_path = '/pub/station/general';

            % target file
            rem_file = 'igs14.atx';
            local_file = state.getAtxFile;

            log.addMessage(log.indent(sprintf(['FTP connection to the IGS server (ftp://' igs_ip ').\nIGS ftp might be slow and the ATX file is approximately 18MB. Please wait...'])));
            %if not(exist([down_dir, '/', s2]) == 2)
            try
                % move the old antex file
                move_success = false;
                if exist(fullfile(local_file), 'file') == 2
                    [move_success, message] = movefile(local_file, [local_file '.old'], 'f');
                    if ~move_success
                        log.addError(message);
                    end
                end
                file_lst = ['http://' igs_ip rem_path '/' rem_file];
                % Download ATX from IGS server
                try
                    f_status_lst = ~isempty(websave(local_file, file_lst));
                catch
                    log.addError('Connection failed.');
                    return
                end
                if ~f_status_lst
                    throw(MException('Verify ATX download', 'download error'));
                end
            catch ex
                % If the FTP is still open (and have been used)
                log.addWarning(sprintf('ATX file have not been updated due to connection problems: %s', ex.message))
                if exist([local_file '.old'], 'file') == 2
                    if move_success
                        [move_success, message] = movefile([local_file '.old'], local_file);
                        if ~move_success
                            err_code = 2;
                            log.addError(message);
                            return
                        end
                    end
                else
                    err_code = 1;
                end
            end
            log.addMessage(log.indent(sprintf('Downloaded ATX file: "%s"\n', local_file)));
            log.addStatusOk('ATX files are present ^_^')
        end
    end

    methods
        function center_list = getAvailableCenters(this)
            % Get all the centers available
            %
            % SYNTAX
            %   center_list = this.getAvailableCenters
            center_list = this.rm.getCenterList();
            [extended, ss] = this.rm.getCenterListExtended();
            center_list = [center_list extended ss];
        end

        function center_list = getAvailableIonoCenters(this)
            % Get all the centers available
            %
            % SYNTAX
            %   center_list = this.getAvailableCenters
            center_list = this.rm.getCenterList(1);
            extended = this.rm.getCenterListExtended(1);
            center_list = [center_list extended];
        end

        function [cur_center, id_center] = getCurCenter(this)
            % Get the current orbit center
            %
            % SYNTAX
            %   [cur_center, id_center] = this.getCurCenter();
            cur_center = Core.getState.getCurCenter();
            center_list = this.rm.getCenterList();
            id_center = find(ismember(center_list, cur_center));
        end

        function setCurCenter(this, cur_center, preferred_type)
            % Set the current orbit center
            %
            % INPUT
            %   cur_center is the name (char or cell) of the center
            %
            % SYNTAX
            %   this.setCurCenter(cur_center, preferred_type);
            %
            % SEE ALSO
            %   getAvailableCenters
            %   setPreferredOrbit
            center_list = this.rm.getCenterList();
            if isnumeric(cur_center)
                cur_center = center_list(cur_center);
            else
                if ischar(cur_center)
                    cur_center = {cur_center};
                end
                if ~ismember(cur_center, center_list)
                    Core.getLogger.addError(sprintf('Unknown center "%s"', cur_center{1}));
                    return
                end
            end
            state = Core.getState;
            state.setCurCenter(cur_center);
            if nargin == 3
                this.setPreferredOrbit(preferred_type);
            else
                this.setPreferredOrbit(true(5,1));
            end
        end

        function [cur_center, id_center] = getCurIonoCenter(this)
            % Get the current orbit center
            %
            % SYNTAX
            %   [cur_center, id_center] = this.getCurCenter();
            cur_center = Core.getState.getCurIonoCenter();
            center_list = this.rm.getCenterList();
            id_center = find(ismember(center_list, cur_center));
        end

        function setCurIonoCenter(this, cur_center, preferred_type)
            % Set the current orbit center
            %
            % INPUT
            %   cur_center is the name (char or cell) of the center
            %
            % SYNTAX
            %   this.setCurCenter(cur_center);
            %
            % SEE ALSO
            %   getAvailableIonoCenters
            %   setPreferredIono
            center_list = this.rm.getCenterList(1);
            if isnumeric(cur_center)
                cur_center = center_list(cur_center);
            else
                if ischar(cur_center)
                    cur_center = {cur_center};
                end
                if ~ismember(cur_center, center_list)
                    Core.getLogger.addError(sprintf('Unknown iono center "%s"', cur_center{1}));
                    return
                end
            end
            state = Core.getState;
            state.setCurIonoCenter(cur_center);
            if nargin == 3
                this.setPreferredIono(preferred_type);
            else
                this.setPreferredIono(true(5,1));
            end
        end

        function [flag, flag_name] = getPreferredOrbit(this)
            % Get the preferred orbit sequence:
            %   1 final
            %   2 rapid
            %   3 ultra
            %   4 broadcast
            %   5 real-time
            %
            % OUPUT
            %   flag is a logical array with 5 values (see above)
            %   flag_name is a cell array with the name of the preference
            %
            % SYNTAX
            %   flag = this.getPreferredOrbit()
            flag = Core.getState.getPreferredOrbit;
            if nargout == 2
                flag_name = {'final', 'rapid', 'ultra', 'broadcast', 'real-time'};
                flag_name = flag_name(flag);
            end
        end

        function setPreferredOrbit(this, flag)
            % Set the preferred orbit sequence:
            %   1 final
            %   2 rapid
            %   3 ultra
            %   4 broadcast
            %   5 real-time
            %
            % INPUT
            %   flag is a logical array with 4 values (see above)
            %   or it can be is a cell array with the name of the preference
            %
            % SYNTAX
            %   this.setPreferredOrbit(flag)

            Core.getState.setPreferredOrbit(flag);
        end

        function [flag, flag_name] = getPreferredIono(this)
            % Get the preferred orbit sequence:
            %   1 final
            %   2 predicted1 (one day ahead)
            %   3 predicted2 (two day ahead)
            %   4 broadcast
            %
            % OUPUT
            %   flag is a logical array with 4 values (see above)
            %   flag_name is a cell array with the name of the preference
            %
            % SYNTAX
            %   flag = this.getPreferredIono()
            flag = Core.getState.getPreferredIono;
            if nargout == 2
                flag_name = {'final', 'rapid', 'predicted1', 'predicted2', 'broadcast'};
                flag_name = flag_name(flag);
            end
        end

        function setPreferredIono(this, flag)
            % Set the preferred orbit sequence:
            %   1 final
            %   2 predicted1 (one day ahead)
            %   3 predicted2 (two day ahead)
            %   4 broadcast
            %
            % INPUT
            %   flag is a logical array with 4 values (see above)
            %   or it can be is a cell array with the name of the preference
            %
            % SYNTAX
            %   this.setPreferredOrbit(flag)

            Core.getState.setPreferredIono(flag);
        end

        function err_code = downloadResource(this, type, date_start, date_stop)
            % Get resourcess:
            %   eph             download ephemeris and clocks
            %   bias            download biases (or differential biases)
            %   crx             download Bernese file with problematic satellits
            %   atm             download atmospheric loading files
            %   iono            download ionex (or other ionosphere products)
            %   iono_brdc       download broadcast Klobuchar parameters
            %   vmf             download vienna mapping fanctions
            %
            % INPUT
            %   type            type of resource to download [char]
            %   date_start      date start [GPS_Time]
            %   date_stop       date stop [GPS_Time]
            %
            % SYNTAX
            %   this.downloadResource(type, date_start, date_stop)
            old_val = Core.getState.isAutomaticDownload;
            Core.getState.setAutomaticDownload(true);
            switch nargin
                case 2
                    err_code = getResource(this, type);
                case 3
                    err_code = getResource(this, type, date_start);
                case 4
                    err_code = getResource(this, type, date_start, date_stop);
            end
            Core.getState.setAutomaticDownload(old_val);
        end

        function err_code = getResource(this, type, date_start, date_stop)
            % Download resourcess:
            %   eph             download ephemeris and clocks
            %   bias            download biases (or differential biases)
            %   crx             download Bernese file with problematic satellits
            %   atm             download atmospheric loading files
            %   iono            download ionex (or other ionosphere products)
            %   iono_brdc       download broadcast Klobuchar parameters
            %   vmf             download vienna mapping fanctions
            %
            % INPUT
            %   type            type of resource to download [char]
            %   date_start      date start [GPS_Time]
            %   date_stop       date stop [GPS_Time]
            %
            % SYNTAX
            %   this.downloadResource(type, date_start, date_stop)

            if nargin < 3
                date_start = this.date_start;
                date_stop = this.date_stop;
            else
                if ischar(date_start)
                    date_start = GPS_Time(date_start);
                    date_stop = GPS_Time(date_stop);
                end

                this.date_start = date_start.getCopy;
                if nargin < 4
                    this.date_stop = date_start.getCopy;
                    this.date_stop.addIntSeconds(86399); % add 1 day
                else
                    this.date_stop = date_stop.getCopy;
                end
            end
            if (GPS_Time.now() - date_stop) < (24*3600)
                this.nrt = true;
            end

            if ~iscell(type)
                type = {type};
            end

            if numel(type) == 1 && strcmp(type{1}, 'all')
                type = {'eph', 'bias', 'crx', 'atm', 'iono', 'iono_brdc', 'vmf', 'igsatx'};
            end

            err_code = {};
            for t = 1 : numel(type)
                cur_type = type{t};
                switch cur_type
                    case {'eph'}
                        err_code{t} = this.conjureNavFiles(date_start, date_stop);
                    case {'bias'}
                        err_code{t} = this.conjureBiasFiles(date_start, date_stop);
                    case {'crx'}
                        err_code{t} = this.conjureCRXFiles(date_start, date_stop);
                    case {'atm'}
                        err_code{t} = this.conjureAtmLoadFiles(date_start, date_stop);
                    case {'iono'}
                        flag_brdc = Core.getState.isIonoKlobuchar();
                        err_code{t} = this.conjureIonoFiles(date_start, date_stop, flag_brdc);
                    case {'iono_brdc'}
                        err_code{t} = this.conjureIonoFiles(date_start, date_stop, true);
                    case {'vmf'}
                        err_code{t} = this.conjureVmfFiles(date_start, date_stop);
                    case {'igsatx'}
                        err_code{t} = this.conjureIGSATXFile();
                end
            end
            if numel(err_code) == 1
                err_code = err_code{1};
            end
        end
    end

end

author: goGPS-Project


text:
function labelfolder(HOMEIMAGES, HOMEANNOTATIONS)
% bb = labelimage(img)
%
% It returns bounding boxes. It does not ask for object names.
% Simple script to label bounding boxes on an image.
%
% Use the online tool for labeling!
%
% Output:
%   bb = bounding boxes. Each row is [xmin ymin width height]

objectname = 'building';

folders = folderlist(HOMEIMAGES);

%f = 4; n = 218;

for f = 5:length(folders)
    imgfiles = dir(fullfile(HOMEIMAGES, folders{f}, '*.jpg'));

    for n = 1:length(imgfiles)
        disp([f n])
        anofile = fullfile(HOMEANNOTATIONS, folders{f}, strrep(imgfiles(n).name, '.jpg', '.xml'));

        todo = 1;
        M = 0;

        % if annotation already exists, skip image
        if exist(anofile, 'file')
            % read annotation file
            clear v
            v = LMread(anofile);

            % check if already annotated
            jc = LMobjectindex(v, objectname);
            if ~isempty(jc)
                todo = 0;
            else
                if isfield(v, 'object')
                    M = length(v.object);
                else
                    M = 0;
                end
            end
        else
            clear v
            v.filename = imgfiles(n).name;
            v.folder = folders{f};
            M = 0;
        end

        if todo
            % check if annotation folder exists
            if ~exist(fullfile(HOMEANNOTATIONS, folders{f}), 'dir')
                mkdir(fullfile(HOMEANNOTATIONS, folders{f}))
            end

            % label image
            img = imread(fullfile(HOMEIMAGES, folders{f}, imgfiles(n).name));
            bb = labelimage(img, v);
            close
            % bb = bounding boxes. Each row is [xmin ymin width height]

            % create annotation struct
            for m = 1:size(bb,1)
                b = bb(m,:);
                x = [b(1) b(1)+b(3) b(1)+b(3) b(1)      b(1)];
                y = [b(2) b(2)      b(2)+b(4) b(2)+b(4) b(2)];
                v.object(M+m).name = objectname;
                v.object(M+m).deleted = '0';
                v.object(M+m).polygon = setLMpolygon(x',y');
            end

            clear xml
            xml.annotation = v;

            % save annotation
            writeXML(anofile, xml);
        end
    end
end

author: CSAILVision

repo: LabelMeToolbox


text:
function asa183_test03 ( )

%*****************************************************************************80
%
%% ASA183_TEST03 tests R8_RANDOM.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ASA183_TEST03\n' );
  fprintf ( 1, '  Show how the seeds used by R8_RANDOM,\n' );
  fprintf ( 1, '  which change on each step, can be reset to\n' );
  fprintf ( 1, '  restore any part of the sequence.\n' );

  s1_save = 12345;
  s2_save = 34567;
  s3_save = 56789;

  s1 = s1_save;
  s2 = s2_save;
  s3 = s3_save;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Begin sequence with following seeds:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  S1 = %d\n', s1 );
  fprintf ( 1, '  S2 = %d\n', s2 );
  fprintf ( 1, '  S3 = %d\n', s3 );
  fprintf ( 1, '\n' );
  fprintf ( 1, '         I      R                 S1        S2        S3\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 10

    [ r, s1, s2, s3 ] = r8_random ( s1, s2, s3 );
    fprintf ( 1, '  %8d  %14f  %8d  %8d  %8d\n', i, r, s1, s2, s3 );

    if ( i == 5 )
      s1_save = s1;
      s2_save = s2;
      s3_save = s3;
    end

  end

  s1 = s1_save;
  s2 = s2_save;
  s3 = s3_save;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Restart the sequence, using the seeds\n' );
  fprintf ( 1, '  produced after step 5:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '         I      R                 S1        S2        S3\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 10

    [ r, s1, s2, s3 ] = r8_random ( s1, s2, s3 );
    fprintf ( 1, '  %8d  %14f  %8d  %8d  %8d\n', i, r, s1, s2, s3 );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% DEMCLASSIFICATION3 IVM for classification on a data-set sampled from a GP with null category.

% IVM

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'classificationThree';
experimentNo = 3;

% load data
[X, y] = mapLoadData(dataSetName);

% Set up model
options = ivmOptions;
options.display = 2;
options.kern = {'rbf', 'white'};

model = ivmCreate(size(X, 1), size(y, 2), X, y, options);

if options.display > 1
  ivm3dPlot(model, 'ivmContour', i);
end
for i = 1:options.extIters;

  % Select the active set.
  model = ivmOptimiseIVM(model, options.display);
  % Plot the data.
  if options.display > 1
    ivm3dPlot(model, 'ivmContour', i);
  end
  % Optimise the kernel parameters.
  model = ivmOptimiseKernel(model, options.display, options.kernIters);
end
model = ivmOptimiseIVM(model, options.display);
if options.display > 1
  ivm3dPlot(model, 'ivmContour', i);
end
% display active points.
model = ivmOptimiseIVM(model, options.display);

% Display the final model.
ivmDisplay(model);

% Save the results.
capName = dataSetName;;
capName(1) = upper(capName(1));
[kern, noise, ivmInfo] = ivmDeconstruct(model);
save(['dem' capName num2str(experimentNo) '.mat'], ...
     'kern', ...
     'noise', ...
     'ivmInfo');

if exist('printDiagram') & printDiagram
  ivmPrintPlot(model, 'ivmContour', [], [], [], capName, experimentNo);
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
%%%%%%%%%%%%%%%%%%%% MRiLab setup%%%%%%%%%%%%%%%%%%%%%%
function MRiLab

    warning off; % disable warning

    [pathstr,name,ext]=fileparts(mfilename('fullpath'));
    addpath(genpath(pathstr));
    % Remove unnessary search path
    rmpath(genpath([pathstr filesep '.git']));
    rmpath(genpath([pathstr filesep 'Doc']));
    % Open MRiLab main panel
    SimuPanel(pathstr);
    clear pathstr name ext
end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function cttools(mode)

f = gcf;
ui_data = get(f,'userdata');
ui_obj = ui_data{2};
eraser2 = ui_obj.eraser2;
tab_uis = ui_obj.ToolTabs;

% define various shades of grey
grey = get(0,'defaultuicontrolbackground');
ltgrey = [0.5,0.5,0.5]*1.5;
dkgrey = [0.5,0.5,0.5]*0.5;

switch mode
   case 'Freq',

      %sel_dims = [-3,0,+6,+2];
      %unsel_dims = [3,0,-6,-2];

      sel_dims = [0,0,0,+2];
      unsel_dims = [0,0,0,-2];

      sel_tab = findobj(f,'tag','selected_tab2');
      cur_obj = tab_uis(1);
      if sel_tab == cur_obj, return; end

      if length(sel_tab),
         tab_pos = get(sel_tab,'pos');
         set(sel_tab,'pos',tab_pos+unsel_dims,'tag','',...
                     'back',ltgrey);
      end

      cur_pos = get(cur_obj,'pos');
      set(cur_obj,'pos',cur_pos+sel_dims,'tag','selected_tab2',...
                  'back',grey);
      eraser_pos = cur_pos+sel_dims;
      set(eraser2,'pos',[eraser_pos(1:3)+[2,0,-4],2]);

      set([ui_obj.RootUI, ui_obj.TimeUI],'vis','off');
      set(ui_obj.FreqUI,'vis','on');

   case 'Root',

      %sel_dims = [-3,0,+6,+2];
      %unsel_dims = [3,0,-6,-2];

      sel_dims = [0,0,0,+2];
      unsel_dims = [0,0,0,-2];

      sel_tab = findobj(f,'tag','selected_tab2');
      cur_obj = tab_uis(2);
      if sel_tab == cur_obj, return; end

      if length(sel_tab),
         tab_pos = get(sel_tab,'pos');
         set(sel_tab,'pos',tab_pos+unsel_dims,'tag','',...
                     'back',ltgrey);
      end

      cur_pos = get(cur_obj,'pos');
      set(cur_obj,'pos',cur_pos+sel_dims,'tag','selected_tab2',...
                  'back',grey);
      eraser_pos = cur_pos+sel_dims;
      set(eraser2,'pos',[eraser_pos(1:3)+[2,0,-4],2]);

      set([ui_obj.FreqUI, ui_obj.TimeUI],'vis','off');
      set(ui_obj.RootUI,'vis','on');

   case 'Time',

      %sel_dims = [-3,0,+6,+2];
      %unsel_dims = [3,0,-6,-2];

      sel_dims = [0,0,0,+2];
      unsel_dims = [0,0,0,-2];

      sel_tab = findobj(f,'tag','selected_tab2');
      cur_obj = tab_uis(3);
      if sel_tab == cur_obj, return; end

      if length(sel_tab),
         tab_pos = get(sel_tab,'pos');
         set(sel_tab,'pos',tab_pos+unsel_dims,'tag','',...
                     'back',ltgrey);
      end

      cur_pos = get(cur_obj,'pos');
      set(cur_obj,'pos',cur_pos+sel_dims,'tag','selected_tab2',...
                  'back',grey);
      eraser_pos = cur_pos+sel_dims;
      set(eraser2,'pos',[eraser_pos(1:3)+[2,0,-4],2]);

      set([ui_obj.FreqUI, ui_obj.RootUI],'vis','off');
      set(ui_obj.TimeUI,'vis','on');

end

author: Sable

repo: mcbench-benchmarks


text:
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
%   BASE64ENCODE(STR, EOL) encode the given string STR.  EOL is the line ending
%   sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
%   The returned encoded string is broken into lines of no more than 76
%   characters each, and each line will end with EOL unless it is empty.  Let
%   EOL be empty if you do not want the encoded string broken into lines.
%
%   STR and EOL don't have to be strings (i.e., char arrays).  The only
%   requirement is that they are vectors containing values in the range 0-255.
%
%   This function may be used to encode strings into the Base64 encoding
%   specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions).  The
%   Base64 encoding is designed to represent arbitrary sequences of octets in a
%   form that need not be humanly readable.  A 65-character subset
%   ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
%   printable character.
%
%   Examples
%   --------
%
%   If you want to encode a large file, you should encode it in chunks that are
%   a multiple of 57 bytes.  This ensures that the base64 lines line up and
%   that you do not end up with padding in the middle.  57 bytes of data fills
%   one complete base64 line (76 == 57*4/3):
%
%   If ifid and ofid are two file identifiers opened for reading and writing,
%   respectively, then you can base64 encode the data with
%
%      while ~feof(ifid)
%         fwrite(ofid, base64encode(fread(ifid, 60*57)));
%      end
%
%   or, if you have enough memory,
%
%      fwrite(ofid, base64encode(fread(ifid)));
%
%   See also BASE64DECODE.

%   Author:      Peter John Acklam
%   Time-stamp:  2004-02-03 21:36:56 +0100
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   % check number of input arguments
   error(nargchk(1, 2, nargin));

   % make sure we have the EOL value
   if nargin < 2
      eol = sprintf('\n');
   else
      if sum(size(eol) > 1) > 1
         error('EOL must be a vector.');
      end
      if any(eol(:) > 255)
         error('EOL can not contain values larger than 255.');
      end
   end

   if sum(size(x) > 1) > 1
      error('STR must be a vector.');
   end

   x   = uint8(x);
   eol = uint8(eol);

   ndbytes = length(x);                 % number of decoded bytes
   nchunks = ceil(ndbytes / 3);         % number of chunks/groups
   nebytes = 4 * nchunks;               % number of encoded bytes

   % add padding if necessary, to make the length of x a multiple of 3
   if rem(ndbytes, 3)
      x(end+1 : 3*nchunks) = 0;
   end

   x = reshape(x, [3, nchunks]);        % reshape the data
   y = repmat(uint8(0), 4, nchunks);    % for the encoded data

   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   % Split up every 3 bytes into 4 pieces
   %
   %    aaaaaabb bbbbcccc ccdddddd
   %
   % to form
   %
   %    00aaaaaa 00bbbbbb 00cccccc 00dddddd
   %
   y(1,:) = bitshift(x(1,:), -2);                  % 6 highest bits of x(1,:)

   y(2,:) = bitshift(bitand(x(1,:), 3), 4);        % 2 lowest bits of x(1,:)
   y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4));   % 4 highest bits of x(2,:)

   y(3,:) = bitshift(bitand(x(2,:), 15), 2);       % 4 lowest bits of x(2,:)
   y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6));   % 2 highest bits of x(3,:)

   y(4,:) = bitand(x(3,:), 63);                    % 6 lowest bits of x(3,:)

   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   % Now perform the following mapping
   %
   %   0  - 25  ->  A-Z
   %   26 - 51  ->  a-z
   %   52 - 61  ->  0-9
   %   62       ->  +
   %   63       ->  /
   %
   % We could use a mapping vector like
   %
   %   ['A':'Z', 'a':'z', '0':'9', '+/']
   %
   % but that would require an index vector of class double.
   %
   z = repmat(uint8(0), size(y));
   i =           y <= 25;  z(i) = 'A'      + double(y(i));
   i = 26 <= y & y <= 51;  z(i) = 'a' - 26 + double(y(i));
   i = 52 <= y & y <= 61;  z(i) = '0' - 52 + double(y(i));
   i =           y == 62;  z(i) = '+';
   i =           y == 63;  z(i) = '/';
   y = z;

   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   % Add padding if necessary.
   %
   npbytes = 3 * nchunks - ndbytes;     % number of padding bytes
   if npbytes
      y(end-npbytes+1 : end) = '=';     % '=' is used for padding
   end

   if isempty(eol)

      % reshape to a row vector
      y = reshape(y, [1, nebytes]);

   else

      nlines = ceil(nebytes / 76);      % number of lines
      neolbytes = length(eol);          % number of bytes in eol string

      % pad data so it becomes a multiple of 76 elements
      y(nebytes + 1 : 76 * nlines) = 0;
      y = reshape(y, 76, nlines);

      % insert eol strings
      eol = eol(:);
      y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));

      % remove padding, but keep the last eol string
      m = nebytes + neolbytes * (nlines - 1);
      n = (76+neolbytes)*nlines - neolbytes;
      y(m+1 : n) = '';

      % extract and reshape to row vector
      y = reshape(y, 1, m+neolbytes);

   end

   % output is a character array
   y = char(y);

repo: REST


text:
function dtiWriteAlgoHeader(headers, fid)

numalgos = length( headers );

for a = 1:numalgos
    algoH = headers(a);

    numchars = length( algoH.name );
    for c = 1:min([numchars 255-1])
        fwrite(fid,algoH.name(c),'char');
    end
    fwrite(fid,char(0),'char');
    for c = min([numchars+2 255+1]):255
        fwrite(fid,'g','char');
    end

    numchars = length( algoH.comments );
    for c = 1:min([numchars 255-1])
        fwrite(fid,algoH.comments(c),'char');
    end
    fwrite(fid,char(0),'char');
    for c = min([numchars+2 255+1]):255
        fwrite(fid,'g','char');
    end

    fwrite(fid,algoH.unique_id,'uint');

    % Write garbage at end for word alignment
    garb_size = dtiGetAlgoHeaderSizeWordAligned() - dtiGetAlgoHeaderSize();
    garbV = zeros(1,garb_size);
    fwrite(fid,garbV,'char');
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
clear psn_3d_mex;
mex psn_3d_mex.c psn_common.c psn_3d.c


text:
function dbunmute
%dbunmute enables all breakpoints currently set in MATLAB.
% Copyright 2009 The MathWorks, Inc.

    % iterate over each entry in the result of dbstatus,
    % and enable each of the breakpoints.
    breakpoints = dbstatus('-completenames');
    for i=1 : length(breakpoints)
        unmuteDbStatusEntry(breakpoints(i));
    end
end

function unmuteDbStatusEntry(dbstatusEntry)
%muteDbStatusEntry disables each breapoint in the given entry.
    for i=1 : length(dbstatusEntry.line)
        file = dbstatusEntry.file;
        line = dbstatusEntry.line(i);
        anonymousIndex = dbstatusEntry.anonymous(i);
        expression = dbstatusEntry.expression{i};

        lineNumberString = [num2str(line) '@' num2str(anonymousIndex)];
        newExpression = stripDisablingPartOfExpression(expression);

        dbstop(file, lineNumberString, 'if', newExpression);
    end
end

function newExpression = stripDisablingPartOfExpression(expression)
%strips any disabling expresion from the given expression.
    if (~isDisabled(expression))
        newExpression = expression;
    elseif strcmp(expression, 'false')
        newExpression = '';
    else
        endPosition = length(expression) - 1;
        newExpression = expression(9:endPosition);
    end
end


text:
function rr = ARS(rel_data, wins, up)
%ARS calculates the power spectral density of a signal using
% auto-regressive modelling, and finds the RR
%
%	            ARS(option, up)
%
%	Inputs:
%       rel_data    .t  vector of times
%                   .v  vector of resp Sig values
%                   .fs sampling freq
%       up              universal parameters structure
%       wins        .t  vector of start times
%
%	Outputs:
%       rr          .t  vector of times of estimated RRs
%                   .v  vector of estimated RRs
%                   .f  vector of freqs of power spectrum
%                   .p  vector of powers of power spectrum
%

%% Setup
downsample_freq = up.paramSet.ar_resample_freq;    % it would be worth changing this - it changes the answer (try 1 Hz e.g.)
true_fs = rel_data.fs;

%% Cycle through windows
rr.t = mean([wins.t_start(:)' ; wins.t_end(:)']); rr.t = rr.t(:);
rr.v = nan(length(rr.t),1);
rr.p = cell(length(wins.t_start),1);
rr.f = cell(length(wins.t_start),1);

for win_no = 1 : length(wins.t_start)

    % extract relevant data
    rel_els = find(rel_data.t >= wins.t_start(win_no) & rel_data.t < wins.t_end(win_no));
    data.v = rel_data.v(rel_els);
    data.t = rel_data.t(rel_els);

    good_els = ~isnan(data.v);
    data.v = data.v(good_els);
    data.t = data.t(good_els);

    % Downsample
    data.filt.t = downsample(data.t, true_fs/downsample_freq);
    data.filt.v = decimate(data.v, true_fs/downsample_freq);
    data.filt.v = detrend(data.filt.v);

    data.filt.v = data.filt.v(:);
    data.filt.t = data.filt.t(:);

    % AR modelling
    [Yy,Xx]=pburg(data.filt.v,up.paramSet.ar_model_order,[],downsample_freq);
    data.freqs=Xx;
    data.power=Yy;

    % Find spectral peak
    [rr.v(win_no), rr.f{win_no}, rr.p{win_no}] = find_spectral_peak(data, up);

    clear data

end

end

author: peterhcharlton

repo: RRest


text:
function res = hlp_checkeegset(EEG,checks)
%
% Check whether EEG dataset(s) contains one or more substructures.
%
% Inputs:
%
%   EEG         EEG dataset or array of datasets
%   checks      Cell vector containing one or more checks to perform
%               Possible checks: {'cat','conn','model','stats','pconn','pnull','surogdist','configs','validation','ic'}.
% Outputs:
%
%   res         cell array containing results of checks where res{i} is the
%               result of checking for checks{i}
%
% Note: hlp_checkeegset('supported_checks'), returns a list of supported
%       checks
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift/
%
%
% Author: Tim Mullen 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

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

res = {};

supported_checks = {'cat','conn','model','stats','pconn','pnull','surogdist','configs','validation','ic'};
if ischar(EEG) && strcmpi(EEG,'supported_checks');
    res = supported_checks;
    return;
end
if nargin<2
    checks = {'cat','conn','model'};
end

if ~iscell(checks)
    checks = {checks};
end

if isempty(EEG)
    res = {sprintf('SIFT: \nEEG structure is empty')};
    return;
end

for cnd=1:length(EEG)
    for i=1:length(checks)
        switch lower(checks{i})
            case 'cat'
                if ~isfield(EEG(cnd),'CAT') || isempty(EEG(cnd).CAT)
                    res = [res, sprintf(['SIFT: \nEEG must contain CAT structure\n' ...
                        'You probably need to complete the pre-processing step first'])];
                end
            case 'conn'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'Conn') ...
                    || isempty(EEG(cnd).CAT.Conn)

                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain Conn structure\n' ...
                        'You need to estimate connectivity first'])];
                end
            case 'model'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'MODEL') ...
                    || isempty(EEG(cnd).CAT.MODEL)
                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain MODEL structure\n' ...
                        'You need to fit a model first'])];
                end
            case 'validation'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'VALIDATION') ...
                    || isempty(EEG(cnd).CAT.VALIDATION)
                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain VALIDATION structure\n' ...
                        'You need to run model validation first'])];
                end
            case 'ic'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'IC') ...
                    || isempty(EEG(cnd).CAT.IC)
                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain IC structure\n' ...
                        'You need to run model order selection first'])];
                end
            case 'surogdist'
                % either pconn OR pnull must be present
                tmpres = hlp_checkeegset(EEG(cnd),{'pnull'});
                if ~isempty(tmpres) % if no pnull, check for pconn...
                    tmpres = hlp_checkeegset(EEG(cnd),{'pconn'});
                end
                res = [res, tmpres];
            case 'pconn'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'PConn') ...
                    || isempty(EEG(cnd).CAT.PConn)

                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain PConn structure\n' ...
                        'You need to estimate connectivity distributions first.\n' ...
                        'See stat_* functions or type ''help stat''.'])];
                end
            case 'pnull'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'Pnull') ...
                    || isempty(EEG(cnd).CAT.Pnull)

                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain Pnull structure\n' ...
                        'You need to estimate a null distribution first.\n' ...
                        'See stat_* functions or type ''help stat''.'])];
                end
            case 'stats'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG(cnd).CAT,'Stats') ...
                    || isempty(EEG(cnd).CAT.Stats)

                    res = [res, sprintf(['SIFT: \nEEG.CAT must contain Stats structure\n' ...
                        'You need to estimate statistics first'])];
                end
            case 'configs'
                if ~isfield(EEG(cnd),'CAT') ...
                    || ~isfield(EEG.CAT,'configs') ...
                    || isempty(EEG.CAT.configs)
                    res = [res, sprintf('SIFT: \nEEG.CAT does not contain a configs structure\n')];
                end
            otherwise
                res = [res, sprintf('SIFT: \nUnknown field/check %s\n',checks{i})];
        end
    end
end


text:
%kkbitor 'Output = Input 1 OR (Input 2 or Constant)'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kbitor.pane file
%
% Parameters:
% InputFile: i1 'Input 1', required: 'First input data object'
% OutputFile: o 'Output', required: 'Resulting output data object'
% InputFile: i2 'Input 2', optional: 'Second input data object'
% Integer: real 'Constant', default: 0: 'Constant value'
%
% Example: o = kkbitor({i1, i2}, {'i1','';'o','';'i2','';'real',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kbitor - Output = Input 1  OR  (Input 2 or Constant)
%
%  DESCRIPTION
% The bitwise OR operator performs a bitwise OR between each point in
% \fBInput 1" and either \fBInput 2\fP or the \fBConstant\fP value, which
% ever is specified by the user.
%
%  "Data Type - Single Input" 5
% .cI $DATAMANIP/repos/shared/man/sections/value_type_1input
%
%  "Data Type - Two Input Objects" 5
% .cI $DATAMANIP/repos/shared/man/sections/value_type_2input
% The bitwise operators will not operate on float or complex data types.
%
%  "Map Data" 5
% The bitwise operations have not been written to be fully polymorphic yet.
% They does not
% check for map data, and will therefore always operate on the value data,
% even if a map exists.  This will most likely corrupt indexing into the map.
% In the case of a single input, it is recommended to use the "Copy to
% Value" (kcptoval) segment operator to temporarily move the map data into
% the value segment, run the bitwise operation on the data, then move it
% back to the map with the "Copy from Value" (kcpfromval) operator.
% When operating with two input objects, where at least one of the objects
% contains map data, data should be mapped prior to running the bitwise
% operator.  The "Map Data" operator (kmapdata) can be used to perform
% the mapping operation.
%
%  "Validity Mask - Single Input" 5
% .cI $DATAMANIP/repos/shared/man/sections/mask_1input
%
%  "Validity Mask - Two Input Objects" 5
% Masking has not been implemented yet for the bitwise operators.  Therefore,
% only the mask from the first input object will be transferred to the output.
%
%  "Input Objects of Different Sizes" 5
% .cI $DATAMANIP/repos/shared/man/sections/resize_2input
% The value used to pad the data when the input files are not the same size is
% zero.
%
%  "Explicit Location and Time Data - Single Input" 5
% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input
%
%  "Explicit Location and Time Data - Two Input Objects" 5
% The bitwise operations have not been extended to understand location and
% time data.  Therefore, only location and time data present in the first input
% object will be transferred to the output.
%
% Executing \fBOR" runs the program "kbitwise\fP with the -or flag.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% DATAMANIP::kbitwise
%
%  RESTRICTIONS
%
% THIS ROUTINE is still under development, and has not been modified to fully
% support the polymorphic data model.  See paragraphs above for discussions
% concerning the polymorphic data segments.
%
% All processing is currently performed as UNSIGNED long, so the operations
% may not work properly on negative values.
%
% The bitwise operators will not operate on float or complex data types.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function rx = rxIn(rx);
%
% rx = rxIn(rx);
%
% For mrRx, nudge the prescription 'in' (along the vector pointing from
% the middle of the last slice toward the middle of the first slice) a
% certain delta according to the value of the nudge slider.
%
% ras, 08/05.
if ieNotDefined('rx')
    cfig = findobj('Tag','rxControlFig');
    rx = get(cfig,'UserData');
end

%%%%%get params
nudgeVal = get(rx.ui.nudge.sliderHandle,'Value')/6; % make a small nudge

%%%%%compute a vector pointing 'in'
% middle X, Y coords
midX = rx.rxDims(2)/2;
midY = rx.rxDims(1)/2;

% cols of coords are: middle of last slice, middle of first slice
coords(:,1) = [midX; midY; rx.rxDims(3)];
coords(:,2) = [midX; midY; 1];

% convert coords into volume coordinate space
volCoords = rx2vol(rx,coords);

% get vector as diff. b/w these two points
vec = diff(volCoords');

%%%%%modify translation accordingly
[trans rot scale skew] = affineDecompose(rx.xform);
trans = trans + nudgeVal.*vec;
newXform = affineBuild(trans,rot,scale,skew);
rx = rxSetXform(rx,newXform);

return


text:
function obj = coeftq2_hand_eye_func_new(in1)
coef_J12 = in1(:,12);
coef_J22 = in1(:,22);
coef_J29 = in1(:,29);
coef_J34 = in1(:,34);
coef_J44 = in1(:,44);
coef_J51 = in1(:,51);
coef_J56 = in1(:,56);
coef_J63 = in1(:,63);
coef_J68 = in1(:,68);
coef_J73 = in1(:,73);
coef_J82 = in1(:,82);
obj = [coef_J12,coef_J22,coef_J29,coef_J34,coef_J44,coef_J51,coef_J56,coef_J63,coef_J68,coef_J73,coef_J82];

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function strcell = numarray2strarray( vec )

N = length(vec);
strcell = cell( 1, N );
for i = 1:N
    strcell{i} = num2str( vec(i) );
end

end

author: andrewssobral

repo: lrslibrary


text:
function low_rank_tensor_completion_embedded()
% Given partial observation of a low rank tensor (possibly including noise),
% attempts to complete it.
%
% function low_rank_tensor_completion_embedded()
%
% NOTE: Tensor Toolbox version 2.6 or higher is required for this factory:
% see https://www.tensortoolbox.org/ or https://gitlab.com/tensors/tensor_toolbox
%
% This example demonstrates how to use the geometry factory for the
% embedded submanifold of fixed-rank tensors in Tucker format:
% fixedranktensorembeddedfactory.
%
% This geometry is described in the article
% "A Riemannian trust-region method for low-rank tensor completion"
% Gennadij Heidel and Volker Schulz, doi:10.1002/nla.2175.
%
% This can be a starting point for many optimization problems of the form:
%
% minimize f(X) such that rank(X) = [r1 ... rd], size(X) = [n1 ... nd].
%
% Important: to keep this example short, the code for the cost function,
% gradient and Hessian do not properly exploit sparsity of the
% observations, which leads to significant slow-downs for large tensors.
% This example file should be considered a starting point for more
% sophisticated implementations.
%
% Input:  None. This example file generates random data with noise.
%
% Output: None.
%
% Please cite the Manopt and Matlab Tensor Toolbox papers as well as the
% research paper:
%     @Article{heidel2018riemannian,
%       Title   = {A {R}iemannian trust-region method for low-rank tensor completion},
%       Author  = {G. Heidel and V. Schulz},
%       Journal = {Numerical Linear Algebra with Applications},
%       Year    = {2018},
%       Volume  = {23},
%       Number  = {6},
%       Pages   = {e1275},
%       Doi     = {10.1002/nla.2175}
%     }
%
% See also: fixedranktensorembeddedfactory

% This file is part of Manopt: www.manopt.org.
% Original author: Gennadij Heidel, January 24, 2019.
% Contributors:
% Change log:

    if ~exist('tenrand', 'file')
        fprintf('Tensor Toolbox version 2.6 or higher is required.\n');
        return;
    end

    % Random data generation with pseudo-random numbers from a
    % uniform distribution on [0, 1].
    tensor_dims = [60 40 20];
    core_dims = [8 6 5];
    total_entries = prod(tensor_dims);
    d = length(tensor_dims);

    % Standard deviation of normally distributed noise.
    % Set sigma to 0 to test the noise-free case.
    sigma = 0.1;

    % Generate a random tensor A of size n1-by-...-by-nd of rank (r1, ..., rd).
    U = cell(1, d);
    R = cell(1, d);
    for i = 1:d
        [U{i}, R{i}] = qr(randn(tensor_dims(i), core_dims(i)), 0);
    end

    Z.U = R;
    Z.G = tenrand(core_dims);
    Core = ttm(Z.G, Z.U);

    Y.U = U;
    Y.G = Core;
    A = ttm(Core, Y.U);

    % Add noise to low-rank tensor
    A = A + sigma*tensor(randn(tensor_dims));

    % Generate a random mask P for observed entries:
    % P(i, j, k) = 1 if the entry (i, j, k) of A is observed,
    %            = 0 otherwise.
    fraction = 0.1; % Fraction of observed entries.
    nr = round(fraction * total_entries);
    ind = randperm(total_entries);
    ind = ind(1 : nr);
    P = false(tensor_dims);
    P(ind) = true;
    % Hence, we observe the nonzero entries in PA:
    P = tensor(P);
    PA = P.*A;
    % Note that an efficient implementation would require evaluating A as a
    % sparse tensor only at the indices of P.

    % Pick the submanifold of tensors of size n1-by-...-by-nd of
    % multilinear rank (r1, ..., rd).
    problem.M = fixedranktensorembeddedfactory(tensor_dims, core_dims);

    % Define the problem cost function.
    % The store structure is used to reduce full tensor evaluations.
    % Again: proper handling of sparse tensors would dramatically reduce
    % the computation time for large tensors. This file only serves as a
    % simple starting point. See help for the Tensor Toolbox regarding
    % sparse tensors. Same comment for gradient and Hessian below.
    problem.cost = @cost;
    function [f, store] = cost(X, store)
        if ~isfield(store, 'PXmPA')
            Xfull = full(X.X);
            store.PXmPA = P.*Xfull - PA;
        end
        f = .5*norm(store.PXmPA)^2;
    end

    % Define the Euclidean gradient of the cost function, that is, the
    % gradient of f(X) seen as a function of X without rank restrictions.
    problem.egrad =  @egrad;
    function [g, store] = egrad(X, store)
        if ~isfield(store, 'PXmPA')
            Xfull = full(X.X);
            store.PXmPA = P.*Xfull - PA;
        end
        g = store.PXmPA;
    end

    % Define the Euclidean Hessian of the cost at X along a vector eta.
    problem.ehess = @ehess;
    function H = ehess(X, eta)
        ambient_H = problem.M.tangent2ambient(X, eta);
        H = P.*ambient_H;
    end

    % Options
    X0 = problem.M.rand();
    options.maxiter = 3000;
    options.maxinner = 100;
    options.maxtime = inf;
    options.storedepth = 3;
    % Target gradient norm
    options.tolgradnorm = 1e-8*problem.M.norm(X0, getGradient(problem, X0));

    % Minimize the cost function using Riemannian trust-regions
    Xtr = trustregions(problem, X0, options);

    % Display some quality metrics for the computed solution
    Xtrfull = full(Xtr.X);
    fprintf('||X-A||_F / ||A||_F = %g\n', norm(Xtrfull - A)/norm(A));
    fprintf('||PX-PA||_F / ||PA||_F = %g\n', norm(P.*Xtrfull - PA)/norm(PA));

end

author: NicolasBoumal

repo: manopt


text:
function value = sweet2_condition ( )

%*****************************************************************************80
%
%% SWEET2_CONDITION returns the L1 condition of the SWEET2 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 February 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real VALUE, the L1 condition.
%
  a_norm = 30.733333333333334;
  b_norm = 1.601605164968818;
  value = a_norm * b_norm;

  return
end