function t = basicinfo(fid,seekset,t)
% T = BASICINFO(FID,SEEKSET,T);
%   FID = valid filepointer to a sqdfile
%   SEEKSET = starting point of file read
%   T = SQDHANDLE OBJECT/STRUCTURE
% Gets the basic info from the file pointed to by fid and returns
% a SQDHANDLE OBJECT if second argument is passed as sqdhandle or
% if no arguemnt is passed or a structure is passsed, it returns a
% structure
if nargin<1
    error('First argument must be valid file-pointer to a sqd-file');
elseif nargin<2
    seekset = -1;
end;

% Get offset of basic information
fseek( fid, 16, seekset );
basic_offset = fread(fid,1,'long');
newline = sprintf('\n');
% Read basic information
fseek( fid, basic_offset, seekset );
tmp.Version	= fread(fid,1,'int');
tmp.Revision	= fread(fid,1,'int');
tmp.SystemID	= fread(fid,1,'int');
tmp.SystemName	= fread(fid,128,'uchar');
tmp.SystemName	= setstr(tmp.SystemName(1:...
    min(find(tmp.SystemName==0)))');
if ~isempty(tmp.SystemName)
    newindx = findstr(tmp.SystemName,newline);
    tmp.SystemName(newindx(end):end) = '';
end;
tmp.ModelName	= fread(fid,128,'uchar');
tmp.ModelName	= setstr(tmp.ModelName(1:...
    min(find(tmp.ModelName==0)))');
if ~isempty(tmp.ModelName)
    newindx = findstr(tmp.ModelName,newline);
    if size(newindx) > 0, tmp.ModelName(newindx(end):end) = ''; end;
end;
tmp.ChannelCount	= fread(fid,1,'int');
tmp.Comment	= fread(fid,256,'uchar');
tmp.Comment	= setstr(tmp.Comment');
if nargin>=2
    taglist = fieldnames(tmp);
    if isa(t,'sqdhandle')
        for i =1:length(taglist)
            t = set(t,taglist{i},getfield(tmp,taglist{i}));
        end;
    elseif istruct(t)
        for i =1:length(taglist)
            t = setfield(t,taglist{i},getfield(tmp,taglist{i}));
        end;
    end;
else
    t = tmp;
end;


function inspect_bug645

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_read_event

filename = dccnpath('/home/common/matlab/fieldtrip/data/test/bug645/Events_ECI_TCPIP_55513.xml');

% there is nothing in this script to be tested automatically
% it only serves to determine the timings once

cd /Volumes/Data/roboos/matlab/fieldtrip/fileio/private
tic; ver1 = xml2struct(filename); toc
% xml2struct reading /home/common/matlab/fieldtrip/data/test/bug645/Events_ECI_TCPIP_55513.xml
% Elapsed time is 22.311995 seconds.

cd /Volumes/Data/roboos/matlab/fieldtrip/external/xml4mat
tic; ver2 = xml2struct(filename); toc
% Elapsed time is 404.807848 seconds.


function varargout=roteu2qr(varargin)
%
% For calling details please see v_roteu2qr.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_roteu2qr.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: roteu2qr.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_roteu2qr(varargin{:});
else
    v_roteu2qr(varargin{:});
end


function wysiwyg
    %WYSIWYG -- this function is called with no args and merely
    %       changes the size of the figure on the screen to equal
    %       the size of the figure that would be printed,
    %       according to the papersize attribute.  Use this function
    %       to give a more accurate picture of what will be
    %       printed.
    %       Dan(K) Braithwaite, Dept. of Hydrology U.of.A  11/93

    unis = get(gcf,'units');
    ppos = get(gcf,'paperposition');
    set(gcf,'units',get(gcf,'paperunits'));
    pos = get(gcf,'position');
    pos(3:4) = ppos(3:4);
    set(gcf,'position',pos);
    set(gcf,'units',unis);


% DETECTOR
% See also
%
% Please see acfReadme for an overview of the detection code.
%
% Aggregate channel features object detector:
%   acfDemoCal   - Demo for aggregate channel features object detector on Caltech dataset.
%   acfDemoInria - Demo for aggregate channel features object detector on Inria dataset.
%   acfDetect    - Run aggregate channel features object detector on given image(s).
%   acfModify    - Modify aggregate channel features object detector.
%   acfReadme    - Aggregate Channel Features Detector Overview.
%   acfSweeps    - Parameter sweeps for ACF pedestrian detector.
%   acfTest      - Test aggregate channel features object detector given ground truth.
%   acfTrain     - Train aggregate channel features object detector.
%
% Object bounding box utilities and labeling tools:
%   bbApply      - Functions for manipulating bounding boxes (bb).
%   bbGt         - Bounding box (bb) annotations struct, evaluation and sampling routines.
%   bbLabeler    - Bounding box or ellipse labeler for static images.
%   bbNms        - Bounding box (bb) non-maximal suppression (nms).


function plotQualityMeasuresForMotionTypes(srResults_globalMotion, srResults_mixedMotion, srResults_localMotion, qualityMeasure, binningFactors, srMethods, normalized, outputDir)

    figure_global = plotQualityMeasuresAsBarplot(srResults_globalMotion, qualityMeasure, binningFactors, srMethods, normalized);
    figure_mixed = plotQualityMeasuresAsBarplot(srResults_mixedMotion, qualityMeasure, binningFactors, srMethods, normalized);
    figure_local = plotQualityMeasuresAsBarplot(srResults_localMotion, qualityMeasure, binningFactors, srMethods, normalized);
    LinkFigures([figure_global figure_mixed figure_local]);

    if normalized
        qualityMeasure = [qualityMeasure, '_norm'];
    end

    % Save to Tikz.
    figure(figure_global);
    matlab2tikz([outputDir, '/', 'baselineDatasets_globalMotion_', qualityMeasure, '.tikz'], ...
        'height', '\figureheight', 'width', '\figurewidth', 'showInfo', false, ...
        'extraaxisoptions', ['xlabel near ticks,', ...
        'ylabel near ticks,', ...
        'scaled y ticks=false,', ...
        'yticklabel style={/pgf/number format/fixed, /pgf/number format/precision=2},']);

    figure(figure_mixed);
    matlab2tikz([outputDir, '/', 'baselineDatasets_mixedMotion_', qualityMeasure, '.tikz'], ...
        'height', '\figureheight', 'width', '\figurewidth', 'showInfo', false, ...
        'extraaxisoptions', ['xlabel near ticks,', ...
        'ylabel near ticks,', ...
        'scaled y ticks=false,', ...
        'yticklabel style={/pgf/number format/fixed, /pgf/number format/precision=2},']);

    figure(figure_local);
    matlab2tikz([outputDir, '/', 'baselineDatasets_localMotion_', qualityMeasure, '.tikz'], ...
        'height', '\figureheight', 'width', '\figurewidth', 'showInfo', false, ...
        'extraaxisoptions', ['xlabel near ticks,', ...
        'ylabel near ticks,', ...
        'scaled y ticks=false,', ...
        'yticklabel style={/pgf/number format/fixed, /pgf/number format/precision=2},']);

function figureNumber = plotQualityMeasuresAsBarplot(srResults, qualityMeasure, binningFactors, srMethods, normalized)

    % Compute mean of the quality measure for different SR methods and
    % binning factors.
    barMeans = zeros(length(binningFactors), length(srMethods));
    for binningFactorIdx = 1:length(binningFactors)
        for srMethodIdx = 1:length(srMethods)
            % Get quality measures for given SR method and binning factor.
            qualityMeasureVals = [srResults([srResults(:).binningFactor] == binningFactors(binningFactorIdx) &  strcmp(srMethods{srMethodIdx}, {srResults(:).srMethod}) > 0).(qualityMeasure)];
            if normalized
                % Normalize the quality measure with the input
                % low-resolution image (after NN interpolation).
                qualityMeasureVals_nn = [srResults([srResults(:).binningFactor] == binningFactors(binningFactorIdx) &  strcmp('nn', {srResults(:).srMethod}) > 0).(qualityMeasure)];
                qualityMeasureVals = (qualityMeasureVals - qualityMeasureVals_nn) ./ abs(qualityMeasureVals_nn);
            end

            % Compute the mean of the quality measure.
            barMeans(binningFactorIdx, srMethodIdx) = mean(qualityMeasureVals);
        end
    end

    % Plot mean quality measures as bar plot.
    figure;
    figureNumber = get(gcf, 'Number');
    bar_handle = bar(barMeans);
    for k = 1:length(srMethods)
        set(bar_handle(k), 'FaceColor', getFaceColorForSRMethod(srMethods{k}));
    end
    hold off;
    pbaspect([4 1.25 1]);
    set(gca, 'XTickLabel', {'2x', '3x', '4x'}, 'XTick', 1:(3*length(srMethods)));
    ymax = max(1.05*max(barMeans(:)));
    ymin = max(0.99*min(barMeans(:)), -0.25*ymax);
    if ymax < ymin
        tmp = ymin;
        ymin = ymax;
        ymax = tmp;
    end
    ylim([ymin ymax]);
    grid on;


% --------------------------------------------------------
% MDP Tracking
% Copyright (c) 2015 CVGL Stanford
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
%
% testing MDP
function metrics = MDP_test_hungarian(seq_idx, seq_set, tracker)

is_show = 0;
is_save = 1;
is_text = 0;
is_pause = 0;

opt = globals();
opt.is_text = is_text;
opt.exit_threshold = 0.7;

if is_show
    close all;
end

if strcmp(seq_set, 'train') == 1
    seq_name = opt.mot2d_train_seqs{seq_idx};
    seq_num = opt.mot2d_train_nums(seq_idx);
else
    seq_name = opt.mot2d_test_seqs{seq_idx};
    seq_num = opt.mot2d_test_nums(seq_idx);
end

% build the dres structure for images
filename = sprintf('%s/%s_dres_image.mat', opt.results, seq_name);
if exist(filename, 'file') ~= 0
    object = load(filename);
    dres_image = object.dres_image;
    fprintf('load images from file %s done\n', filename);
else
    dres_image = read_dres_image(opt, seq_set, seq_name, seq_num);
    fprintf('read images done\n');
    save(filename, 'dres_image', '-v7.3');
end

% read detections
filename = fullfile(opt.mot, opt.mot2d, seq_set, seq_name, 'det', 'det.txt');
dres_det = read_mot2dres(filename);

if strcmp(seq_set, 'train') == 1
    % read ground truth
    filename = fullfile(opt.mot, opt.mot2d, seq_set, seq_name, 'gt', 'gt.txt');
    dres_gt = read_mot2dres(filename);
    dres_gt = fix_groundtruth(seq_name, dres_gt);
end

% load the trained model
if nargin < 3
    object = load('tracker.mat');
    tracker = object.tracker;
end

% intialize tracker
I = dres_image.I{1};
tracker = MDP_initialize_test(tracker, size(I,2), size(I,1), dres_det, is_show);

% for each frame
trackers = [];
id = 0;
for fr = 1:seq_num
    if is_text
        fprintf('frame %d\n', fr);
    else
        fprintf('.');
        if mod(fr, 100) == 0
            fprintf('\n');
        end
    end

    % extract detection
    index = find(dres_det.fr == fr);
    dres = sub(dres_det, index);

    % nms
%     boxes = [dres.x dres.y dres.x+dres.w dres.y+dres.h dres.r];
%     index = nms_new(boxes, 0.6);
%     dres = sub(dres, index);

    dres = MDP_crop_image_box(dres, dres_image.Igray{fr}, tracker);

    if is_show
        figure(1);

        % show ground truth
        if strcmp(seq_set, 'train') == 1
            subplot(2, 2, 1);
            show_dres(fr, dres_image.I{fr}, 'GT', dres_gt);
        end

        % show detections
        subplot(2, 2, 2);
        show_dres(fr, dres_image.I{fr}, 'Detections', dres_det);
    end

    % separate trackers into the first and the second class
    [index1, index2] = sort_trackers(trackers);

    for k = 1:2
        % process trackers in the first class or the second class
        if k == 1
            index_track = index1;
        else
            index_track = index2;
        end

        num_track = numel(index_track);
        flags = zeros(num_track, 1);

        % process tracked targets
        for i = 1:num_track
            ind = index_track(i);
            if trackers{ind}.state == 0
                flags(i) = 1;
            elseif trackers{ind}.state == 2
                % track target
                trackers{ind} = track(fr, dres_image, dres, trackers{ind}, opt);
                % connect target
                if trackers{ind}.state == 3
                    if k == 1
                        index_tmp = index_track(1:i-1);
                    else
                        index_tmp = [index_track(1:i-1); index1];
                    end
                    [dres_tmp, index] = generate_initial_index(trackers(index_tmp), dres);
                    dres_associate = sub(dres_tmp, index);
                    trackers{ind} = associate(fr, dres_image,  dres_associate, trackers{ind}, opt);
                end

                if trackers{ind}.state == 2 || trackers{ind}.state == 0
                    flags(i) = 1;
                end
            end
        end

        % process lost targets
        if k == 1
            index_tmp = index_track(flags == 1);
        else
            index_tmp = [index_track(flags == 1); index1];
        end
        [dres_tmp, index] = generate_initial_index(trackers(index_tmp), dres);
        dres_associate = sub(dres_tmp, index);
        num_det = numel(index);

        % compute distance matrix
        index_track = index_track(flags == 0);
        num_track = numel(index_track);
        dist = zeros(num_track, num_det);
        for i = 1:num_track
            % lost target
            ind = index_track(i);
            dist(i,:) = compute_distance(fr, dres_image, dres_associate, trackers{ind});
        end

        % Hungarian algorithm
        assignment = assignmentoptimal(dist);

        % process the assignment
        for i = 1:numel(assignment)
            det_id = assignment(i);
            ind = index_track(i);
            if det_id == 0
                % no association
                trackers{ind}.state = 3;
                dres_one = sub(trackers{ind}.dres, numel(trackers{ind}.dres.fr));
                dres_one.fr = fr;
                dres_one.id = trackers{ind}.target_id;
                dres_one.state = 3;

                if trackers{ind}.dres.fr(end) == fr
                    dres_tmp = trackers{ind}.dres;
                    index_tmp = 1:numel(dres_tmp.fr)-1;
                    trackers{ind}.dres = sub(dres_tmp, index_tmp);
                end
                trackers{ind}.dres = concatenate_dres(trackers{ind}.dres, dres_one);
            else
                % association
                dres_one = sub(dres_associate, det_id);
                trackers{ind} = LK_associate(fr, dres_image, dres_one, trackers{ind});

                trackers{ind}.state = 2;
                % build the dres structure
                dres_one = [];
                dres_one.fr = fr;
                dres_one.id = trackers{ind}.target_id;
                dres_one.x = trackers{ind}.bb(1);
                dres_one.y = trackers{ind}.bb(2);
                dres_one.w = trackers{ind}.bb(3) - trackers{ind}.bb(1);
                dres_one.h = trackers{ind}.bb(4) - trackers{ind}.bb(2);
                dres_one.r = 1;
                dres_one.state = 2;

                if trackers{ind}.dres.fr(end) == fr
                    dres_tmp = trackers{ind}.dres;
                    index_tmp = 1:numel(dres_tmp.fr)-1;
                    trackers{ind}.dres = sub(dres_tmp, index_tmp);
                end
                trackers{ind}.dres = interpolate_dres(trackers{ind}.dres, dres_one);
                % update LK tracker
                trackers{ind} = LK_update(fr, trackers{ind}, dres_image.Igray{fr}, dres_associate, 1);
            end
        end
    end

    % find detections for initialization
    [dres, index] = generate_initial_index(trackers, dres);
    for i = 1:numel(index)
        % extract features
        dres_one = sub(dres, index(i));
        f = MDP_feature_active(tracker, dres_one);
        % prediction
        label = svmpredict(1, f, tracker.w_active, '-q');
        % make a decision
        if label < 0
            continue;
        end

        % reset tracker
        tracker.prev_state = 1;
        tracker.state = 1;
        id = id + 1;

        trackers{end+1} = initialize(fr, dres_image, id, dres, index(i), tracker);
    end

    % resolve tracker conflict
    trackers = resolve(trackers, dres, opt);

    dres_track = generate_results(trackers);
    if is_show
        figure(1);

        % show tracking results
        subplot(2, 2, 3);
        show_dres(fr, dres_image.I{fr}, 'Tracking', dres_track, 2);

        % show lost targets
        subplot(2, 2, 4);
        show_dres(fr, dres_image.I{fr}, 'Lost', dres_track, 3);

        if is_pause
            pause();
        else
            pause(0.01);
        end
    end
end

% write tracking results
filename = sprintf('%s/%s.txt', opt.results, seq_name);
fprintf('write results: %s\n', filename);
write_tracking_results(filename, dres_track, opt.tracked);

% evaluation
if strcmp(seq_set, 'train') == 1
    benchmark_dir = fullfile(opt.mot, opt.mot2d, seq_set, filesep);
    metrics = evaluateTracking({seq_name}, opt.results, benchmark_dir);
else
    metrics = [];
end

% save results
if is_save
    filename = sprintf('%s/%s_results.mat', opt.results, seq_name);
    save(filename, 'dres_track', 'metrics');
end

% sort trackers according to number of tracked frames
function [index1, index2] = sort_trackers(trackers)

sep = 10;
num = numel(trackers);
len = zeros(num, 1);
state = zeros(num, 1);
for i = 1:num
    len(i) = trackers{i}.streak_tracked;
    state(i) = trackers{i}.state;
end

index1 = find(len > sep);
[~, ind] = sort(state(index1));
index1 = index1(ind);

index2 = find(len <= sep);
[~, ind] = sort(state(index2));
index2 = index2(ind);

% initialize a tracker
% dres: detections
function tracker = initialize(fr, dres_image, id, dres, ind, tracker)

if tracker.state ~= 1
    return;
else  % active

    % initialize the LK tracker
    tracker = LK_initialize(tracker, fr, id, dres, ind, dres_image);
    tracker.state = 2;
    tracker.streak_occluded = 0;
    tracker.streak_tracked = 0;

    % build the dres structure
    dres_one.fr = dres.fr(ind);
    dres_one.id = tracker.target_id;
    dres_one.x = dres.x(ind);
    dres_one.y = dres.y(ind);
    dres_one.w = dres.w(ind);
    dres_one.h = dres.h(ind);
    dres_one.r = dres.r(ind);
    dres_one.state = tracker.state;
    tracker.dres = dres_one;
end

% track a target
function tracker = track(fr, dres_image, dres, tracker, opt)

% tracked
if tracker.state == 2
    tracker.streak_occluded = 0;
    tracker.streak_tracked = tracker.streak_tracked + 1;
    tracker = MDP_value(tracker, fr, dres_image, dres, []);

    % check if target outside image
    [~, ov] = calc_overlap(tracker.dres, numel(tracker.dres.fr), dres_image, fr);
    if ov < opt.exit_threshold
        if opt.is_text
            fprintf('target outside image by checking boarders\n');
        end
        tracker.state = 0;
    end
end

% associate a lost target
function tracker = associate(fr, dres_image, dres_associate, tracker, opt)

% occluded
if tracker.state == 3
    tracker.streak_occluded = tracker.streak_occluded + 1;
    % find a set of detections for association
    [dres_associate, index_det] = generate_association_index(tracker, fr, dres_associate);
    tracker = MDP_value(tracker, fr, dres_image, dres_associate, index_det);
    if tracker.state == 2
        tracker.streak_occluded = 0;
    end

    if tracker.streak_occluded > opt.max_occlusion
        tracker.state = 0;
        if opt.is_text
            fprintf('target %d exits due to long time occlusion\n', tracker.target_id);
        end
    end

    % check if target outside image
    [~, ov] = calc_overlap(tracker.dres, numel(tracker.dres.fr), dres_image, fr);
    if ov < opt.exit_threshold
        if opt.is_text
            fprintf('target outside image by checking boarders\n');
        end
        tracker.state = 0;
    end
end

% associate a lost target
function dist = compute_distance(fr, dres_image, dres_associate, tracker)

% occluded
if tracker.state == 3
    % find a set of detections for association
    [dres_associate, index_det] = generate_association_index(tracker, fr, dres_associate);

    % compute association scores
    num = numel(dres_associate.fr);
    dist = Inf(1, num);
    if isempty(index_det) == 0
        % extract features with LK association
        dres = sub(dres_associate, index_det);
        [features, flag] = MDP_feature_occluded(fr, dres_image, dres, tracker);

        m = size(features, 1);
        labels = -1 * ones(m, 1);
        [~, ~, probs] = svmpredict(labels, features, tracker.w_occluded, '-b 1 -q');

        dist(index_det(flag == 1)) = probs(flag == 1, 2);
        dist(dist > 0.5) = inf;
    end
end

% resolve conflict between trackers
function trackers = resolve(trackers, dres_det, opt)

% collect dres from trackers
dres_track = [];
for i = 1:numel(trackers)
    tracker = trackers{i};
    dres = sub(tracker.dres, numel(tracker.dres.fr));

    if tracker.state == 2
        if isempty(dres_track)
            dres_track = dres;
        else
            dres_track = concatenate_dres(dres_track, dres);
        end
    end
end

% compute overlaps
num_det = numel(dres_det.fr);
if isempty(dres_track)
    num_track = 0;
else
    num_track = numel(dres_track.fr);
end

flag = zeros(num_track, 1);
for i = 1:num_track
    [~, o] = calc_overlap(dres_track, i, dres_track, 1:num_track);
    o(i) = 0;
    o(flag == 1) = 0;
    [mo, ind] = max(o);
    if mo > opt.overlap_sup
        num1 = trackers{dres_track.id(i)}.streak_tracked;
        num2 = trackers{dres_track.id(ind)}.streak_tracked;
        o1 = max(calc_overlap(dres_track, i, dres_det, 1:num_det));
        o2 = max(calc_overlap(dres_track, ind, dres_det, 1:num_det));

        if num1 > num2
            sup = ind;
        elseif num1 < num2
            sup = i;
        else
            if o1 > o2
                sup = ind;
            else
                sup = i;
            end
        end

        trackers{dres_track.id(sup)}.state = 3;
        trackers{dres_track.id(sup)}.dres.state(end) = 3;
        if opt.is_text
            fprintf('target %d suppressed\n', dres_track.id(sup));
        end
        flag(sup) = 1;
    end
end


function button = rxMakeButton(name,pos,direc);
%  button = rxMakeButton(name,pos,[direc]);
%
% Make a radio button for mrRx, with
% the specified name and position.
%
% If a cell of names is specified,
% will make a vertical set of radio
% buttons, one for each entry, filling
% up the box specified by pos.
%
% direc: direction flag--only of relevance
% for multiple buttons. If 0 [default],
% stack buttons vertically; otherwise, place
% horizontally.
%
% Returns a vector of handles to the buttons.
%
% ras 02/05.
if ieNotDefined('direc')
    direc = 0;
end

if iscell(name)
    % recursively make buttons
    nButtons = length(name);
    for i = 1:nButtons
        subpos = pos;
        if direc==0
            % stack vertically
            subpos(2) = pos(2) + (i-1)*pos(4)/nButtons;
            subpos(4) = pos(4)/nButtons;
        else
            % place horizontally
            subpos(1) = pos(1) + (i-1)*pos(3)/nButtons;
            subpos(3) = pos(3)/nButtons;
        end
        button(i) = rxMakeButton(name{i},subpos,direc);

        % new callback:
        cbstr = sprintf('selectButton(get(gcbo,''UserData''),%i);',i);
        cbstr = sprintf('%s \n rxRefresh;',cbstr);
        set(button(i),'Callback',cbstr);
    end
    set(button,'UserData',button,'Style','radiobutton');
    return
end

button = uicontrol('Style','checkbox',...
                   'Units','Normalized',...
                   'Position',pos,...
                   'String',name,...
                   'Min',0,'Max',1,...
                   'Value',0,...
                   'BackgroundColor',get(gcf,'Color'),...
                   'ForegroundColor',[.3 .3 .3],...
                   'Callback','rxRefresh;');

return


classdef nme_shunt_acp < mp.nme_shunt_ac & mp.form_acp

%   MATPOWER
%   Copyright (c) 2019-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end     %% properties

%     methods
%     end     %% methods
end         %% classdef


  function fmap = mri_field_map_cyl()
%| synthesize field map associated with a cylinder of uniform susceptibility
%| within an extended object also having uniform susceptibility
%| cylinder is aligned with static field

% todo: use
%| lucas:93:dii
%| aksit:07:tpm
%| yoder:04:msw

fail 'todo'


function d =  testing(a,d)

 d=test(a.child,d);
 d.X=mean(d.X)';

 d=set_name(d,[get_name(d) ' -> ' get_name(a)]);


% mff_exportevents - export MFF EEG event from EEGLAB structure to
%                    'Events_exported_from_EEGLAB.xml' file
% Usage:
%   mff_exportevents(EEG, mffFile);
%
% Inputs:
%  EEG     - EEGLAB structure
%  mffFile - filename/foldername for the MFF file (MFF file/folder must
%            already exist)

% This file is part of mffmatlabio.
%
% mffmatlabio 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.
%
% mffmatlabio 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 mffmatlabio.  If not, see <https://www.gnu.org/licenses/>.

function mff_exportevents(EEG, mffFile)

p = fileparts(which('mff_importsignal.m'));
warning('off', 'MATLAB:Java:DuplicateClass');
javaaddpath(fullfile(p, 'MFF-1.2.2-jar-with-dependencies.jar'));
warning('on', 'MATLAB:Java:DuplicateClass');

if isfield(EEG.etc, 'recordingtime')
    begTime = EEG.etc.recordingtime;
else
    begTime = now;
end
if isfield(EEG.etc, 'timezone')
    timeZone = EEG.etc.timezone;
else
    timeZone = '00:00';
end
srate    = EEG.srate;

% create a factory
mfffactorydelegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
mfffactory = javaObject('com.egi.services.mff.api.MFFFactory', mfffactorydelegate);

% determine the number of files
events   = EEG.event;
if isfield(EEG.event, 'name')
    allNames = { events.name };
    allNames = cellfun(@num2str, allNames, 'UniformOutput', false);
    uniqueNames = unique( allNames );
else
    uniqueNames = { '' };
end

tracktype = '';
for iFile = 1:length(uniqueNames)

    % Create Signal object and read in event track file.
    fileName = 'Events_exported_from_EEGLAB.xml';
    if length(uniqueNames) > 1
        eventtrackfilename = fullfile(mffFile, [ fileName(1:end-4) '_' num2str(iFile) '.xml' ]);
        indEvents = strmatch( uniqueNames{iFile}, allNames, 'exact');
        if isfield(events, 'tracktype')
            tracktype = events(indEvents(1)).tracktype;
        end
    else
        eventtrackfilename = fullfile(mffFile, fileName);
        if isfield(events, 'tracktype')
            tracktype = events(1).tracktype;
        end
        indEvents = 1:length(events);
    end

    if ~all(cellfun(@(x)isequal(x, 'boundary'), {events(indEvents).type}))
        eventtracktype = javaObject('com.egi.services.mff.api.MFFResourceType', javaMethod('valueOf', 'com.egi.services.mff.api.MFFResourceType$MFFResourceTypes', 'kMFF_RT_EventTrack'));
        if mfffactory.createResourceAtURI(eventtrackfilename, eventtracktype)
            disp('Success at creating the event file');
        else
            disp('Could not create event file');
        end

        fprintf('Exporting %d events...\n', length(events));
        eventtrackObj = mfffactory.openResourceAtURI(eventtrackfilename, eventtracktype);
        if isfield(events, 'name') && ~isempty(uniqueNames{iFile})
            eventtrackObj.setName(events(1).name);
        end
        if isfield(events, 'tracktype') && ~isempty(tracktype)
            eventtrackObj.setTrackType(tracktype);
        end

        jList = javaObject('java.util.ArrayList');
        addLatency = 0;
        multiplier = 24*60*60*srate;
        keyWarning = true;
        for iEvent = 1:length(events)
            if strcmpi(events(iEvent).type, 'boundary') % do not export boundary events
                addLatency = addLatency + events(iEvent).duration;
            else
                if ~isfield(events, 'name') || strcmpi(events(iEvent).name, uniqueNames{iFile})
                    eventObj = javaObject('com.egi.services.mff.api.Event');

                    % Get keys for event and display key codes
                    if isfield(events(iEvent), 'code')
                        eventObj.setCode(        events(iEvent).code );
                    else
                        eventObj.setCode(num2str(events(iEvent).type));
                    end
                    if isfield(events(iEvent), 'description'),  eventObj.setDescription( events(iEvent).description ); end
                    if isfield(events(iEvent), 'duration'   ),  eventObj.setDuration(    events(iEvent).duration ); end
                    if isfield(events(iEvent), 'label'),        eventObj.setLabel(       events(iEvent).label ); end
                    if isfield(events(iEvent), 'sourcedevice'), eventObj.setSourceDevice(events(iEvent).sourcedevice ); end

                    if isfield(events, 'mffkeysbackup') && ~isempty(events(iEvent).mffkeysbackup)
                        jListKeys = javaObject('java.util.ArrayList');
                        tmpmffkeysbackup = events(iEvent).mffkeysbackup;
                        tmpmffkeysbackup(tmpmffkeysbackup == 10) = ' '; % remove carriage return
                        tmpKeys = eval(tmpmffkeysbackup);
                        for iKey = 1:length(tmpKeys);
                            keyObj = javaObject('com.egi.services.mff.api.Key');
                            keyObj.setCode(tmpKeys(iKey).code);
                            keyObj.setData(tmpKeys(iKey).data);
                            keyObj.setDataType(tmpKeys(iKey).datatype);
                            keyObj.setDescription(tmpKeys(iKey).description);
                            jListKeys.add(keyObj);
                        end
                        eventObj.setKeys(jListKeys);
                    elseif keyWarning
                        disp('Warning: no MFF backup key structure found - MFF keys not exported');
                        disp('         import keys when loading the data to be able to export them');
                        keyWarning = false;
                    end

                    realLatency = (events(iEvent).latency + addLatency)/multiplier+begTime;
                    tmp = mff_encodetime(realLatency, timeZone);
                    if isfield(events(iEvent), 'begintime')
                        if ~isequal(events(iEvent).begintime, tmp) && ~isempty(events(iEvent).begintime)
                            fprintf('Note: exported event time %d differ from original one %s vs %s\n', iEvent, events(iEvent).begintime, tmp);
                        end
                    end
                    eventObj.setBeginTime(mff_encodetime(realLatency, timeZone));

                    jList.add(eventObj);
                end
            end
        end
        eventtrackObj.setEvents(jList);
        eventtrackObj.saveResource();
    end
end


function this = blank(this, fnamedat)
% Creates a blank datafile matching in the header in dimensions
% Will not erase existing datafile it it's there
% FORMAT this = blank(this)
%   Will create the datafile using fname and path
% FORMAT this = blank(this, fnamedat)
%   Will create the datafile using the provided name and path
% _________________________________________________________________________
% Copyright (C) 2011-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: blank.m 5648 2013-09-23 12:40:40Z vladimir $

if nargin == 1
    [p, f] = fileparts(fullfile(this));
    fnamedat = fullfile(p, [f '.dat']);
else
   [p, f, x] = fileparts(fnamedat);
   if isempty(p)
       p = path(this);
   end
   if isempty(x)
       x = '.dat';
   end
   fnamedat = fullfile(p, [f x]);
end

if exist(fnamedat, 'file')
    error('Data file exists. Use rmdata to delete.')
end

if isempty(this)
   error('All header dimensions should be >0');
end

this.data = file_array(fnamedat, size(this), 'float32-le');

initialise(this.data);

this = check(this);


function vis_sticks_waf(img,pred_stickmen,gt_stickmen,evalidx,scoredetail,fname)

% plot predicted sticks, upper body detections and GT sticks
% predicted and GT sticks are only plotted for upper body detections
% that match the GT upper body bounding boxes

clf; imagesc(img); axis equal; axis  off; hold on;
for ridx = 1:length(gt_stickmen)
    if (evalidx(ridx) ~= 0) % upper body detection matches GT bounding box
        % plot detection
        sc = scoredetail;
%         if (sc{ridx}(6) == 0) % head prediction is wrong
        if (sc{ridx}(1) == 0) % torso prediction is wrong
            c = 'y';
        else
            c = 'r';
        end
        b = pred_stickmen(evalidx(ridx)).det;
        rectangle('Pos',[b(1) b(2) b(3)-b(1) b(4)-b(2)],'lineWidth',2,'edgeColor',c);

        % plot number of parts estimated correctly / total number of parts
        text(b(1),b(2),sprintf('%d/%d',sum(sc{ridx}),numel(sc{ridx})),'FontSize',10,'color','k','BackgroundColor','g',...
            'verticalalignment','top','horizontalalignment','left');
        DrawStickman(pred_stickmen(evalidx(ridx)).coor,[]);
    end
end
print(gcf,'-dpng',[fname '.png']);
% draw a subset of GT poses for which evaluation is performed
clf; imagesc(img); axis equal; axis  off; hold on;
for ridx = 1:length(gt_stickmen)
    if (evalidx(ridx) ~= 0) % upper body detection matches GT bounding box
        DrawStickman(gt_stickmen(ridx).coor,[]);
    end
end
print(gcf,'-dpng',[fname '_gt.png']);
unix(['montage ' fname '.png' ' ' fname '_gt.png' ' -geometry +0+0 ' fname '_combo.png']);
end


function list = dirext(path, varargin)
% DIREXT Extended version of standard dir command.
% ------------------------------------------------------------------------------
% SYNTAX
% 1 list = dirext(path)
%     Lists all files and folders contained in path.
%
% 2 list = dirext(path, Filter)
%     With Filter a filtering of the files and folders can be performed.
% ------------------------------------------------------------------------------
% INPUT
% 1 path
%     Search path.
%
% 2 [Filter]
%     String or cell array of strings containing filter informations. All
%     options offered by the original dir command are possible. Among them
%     possible choices are:
%       * 'isdir'    Output list contains just folders.
% ------------------------------------------------------------------------------
% OUTPUT
% 1 list
%     List of files and/or folders, found in path. Result is cell array.
% ------------------------------------------------------------------------------
% EXAMPLES
% 1 List all files and folders in current folder.
%     dirext('*')
%
% 2 List all files and folders in Y:\Temp\.
%     dirext('Y:\Temp')
%
% 3 List just folders in Y:\Temp\.
%     dirext('Y:\Temp', 'isdir')
% ------------------------------------------------------------------------------
% philipp.glira@gmail.com
% ------------------------------------------------------------------------------

% Input parsing ----------------------------------------------------------------

p = inputParser;
p.addRequired('path',     @ischar);
p.addOptional('Filter', [], @(x) ischar(x) || iscell(x));
p.parse(path, varargin{:});
p = p.Results;
% Clear required inputs to avoid confusion
clear path

% Create raw list of files/folders ---------------------------------------------

listStruct = dir(p.path);

% Error if no files or folders are found
if isempty(listStruct), error('No files or folders found.'); end

% Delete two first entries ('.' and '..') if present
idxLogPoint  = strcmp({listStruct.name}, '.');  % where is point?
idxLogDPoint = strcmp({listStruct.name}, '..'); % where is double point?
idxLog = idxLogPoint | idxLogDPoint;
% Delete if found
if any(idxLog), listStruct(idxLog) = []; end

% Filtering of results? --------------------------------------------------------

if ~isempty(p.Filter)

    % Just folders
    if strcmpi(p.Filter, 'isdir')
        LogIdx = ([listStruct.isdir] == 1);
        listStruct = listStruct(LogIdx);
    end

end

list = {listStruct.name};


classdef mp_idx_manager < handle
%MP_IDX_MANAGER  MATPOWER Index Manager abstract class
%
%   A MATPOWER Index Manager object can be used to manage the indexing of
%   various named and indexed blocks of various set types, such as variables,
%   constraints, etc. This class helps keep track of the ordering and
%   indexing of the various blocks as they are added to the object.
%
%   The types of named sets to be managed by the class are defined by the
%   DEF_SET_TYPES method, which assigns a struct to the 'set_types' field.
%
%   Properties:
%       set_types   - a struct defined by DEF_SET_TYPES method
%       userdata    - a struct containing arbitrary data added by the user
%
%   Private Methods
%       add_named_set - Adds named subset of a particular type to the
%           object.
%
%       def_set_types - (must be implemented in the subclass) Returns a
%           struct defining the various set types, where the key is the
%           set type name, which must also be declared as a property in
%           the object's class, and the value is a string name used for
%           display purposes.
%
%           E.g.
%               function obj = def_set_types(obj)
%                   obj.set_types = struct(...
%                           'var', 'variable', ...
%                           'lin', 'linear constraint' ...
%                       );
%               end
%
%       init_set_types - Initializes the structures needed to track the
%           ordering and indexing of each set type and can be overridden
%           to initialize any additional data to be stored with each block
%           of each set type. Ideally, this would be called at the end
%           of the MP_IDX_MANAGER constructor, but this is not possible
%           in Octave 5.2 and earlier due to a bug related to altering
%           fields of an object not yet fully constructed.
%           Fixed in Octave v6.x: https://savannah.gnu.org/bugs/?52614
%           The workaround is to be sure that this method is called by
%           some subclass method(s) after object construction, but before
%           any other use (e.g. in display() and add_*() methods).
%
%       valid_named_set_type - Returns a label for the given named set
%           type if valid, empty otherwise.
%
%   Public Methods
%       add_<SET-TYPE> - (must be implemented in the subclass) Used to
%           add a block of the given set type to the object, using the
%           private ADD_NAMED_SET method internally followed by the
%           handling of any data specific to that set type.
%
%       copy - Makes a shallow copy of the object.
%
%       describe_idx - Identifies indices of a given set type.
%           E.g. variable 361 corresponds to Pg(68)
%
%       display - (must be implemented in the subclass) Displays the
%           object (called automatically when you omit the semicolon at
%           the command-line).
%
%       display_set - Prints to screen the indexing details for the
%           specified set type. Intended to be called by DISPLAY method.
%
%       get_idx - Returns index structure(s) for specified set type(s),
%           with starting/ending indices and number of elements for
%           each named (and optionally indexed) block.
%
%       get_userdata - Retreives values of user data stored in the object.
%
%       get - Return the value of any individual field.
%
%       getN - Returns the number of elements of any given set type,
%           optionally for a single named block.
%
%       init_indexed_name - Initializes the dimensions for an indexed
%           named set.
%
%       params_<SET-TYPE> - (must be implemented in the subclass)
%           Returns set-type-specific data for a given type.
%
%   The following is the structure of the data in the object, using a set
%   type named 'var' for illustration. Each field of .idx or .data is a
%   struct whose field names are the names of the corresponding blocks of
%   elements of that type (e.g. variables, constraints, etc.). They are
%   found in order in the corresponding .order field. The description next
%   to these fields gives the meaning of the value for each named sub-field.
%   E.g. obj.var.data.v0.Pg contains a vector of initial values for the 'Pg'
%   block of variables.
%
%   obj
%       .var        - data for 'var' set type, e.g. variable sets that
%                     make up the full optimization variable x
%           .idx
%               .i1 - starting index within x
%               .iN - ending index within x
%               .N  - number of elements in this variable set
%           .N      - total number of elements in x
%           .NS     - number of variable sets or named blocks
%           .data   - additional set-type-specific data for each block
%           .order  - struct array of names/indices for variable
%                     blocks in the order they appear in x
%               .name   - name of the block, e.g. Pg
%               .idx    - indices for name, {2,3} => Pg(2,3)
%       .userdata   - any user defined data
%           .(user defined fields)

%   MP-Opt-Model
%   Copyright (c) 2008-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

%    es = struct();

    properties
        userdata = struct();
        set_types
    end     %% properties

    methods
        %% constructor
        function obj = mp_idx_manager(s)
            if nargin > 0
                if isa(s, 'mp_idx_manager')
                    %% this copy constructor will not be inheritable under
                    %% Octave until the fix has been included for:
                    %%      https://savannah.gnu.org/bugs/?52614
                    if have_feature('octave')
                        s1 = warning('query', 'Octave:classdef-to-struct');
                        warning('off', 'Octave:classdef-to-struct');
                    end
                    props = fieldnames(s);
                    if have_feature('octave')
                        warning(s1.state, 'Octave:classdef-to-struct');
                    end
                    for k = 1:length(props)
                        obj.(props{k}) = s.(props{k});
                    end
                elseif isstruct(s)
                    props = fieldnames(obj);
                    for k = 1:length(props)
                        if isfield(s, props{k})
                            obj.(props{k}) = s.(props{k});
                        end
                    end
                else
                    error('@mp_idx_manager/mp_idx_manager: input must be an ''mp_idx_manager'' object or a struct');
                end
            end

            obj.def_set_types();

            %% The INIT_SET_TYPES() method should ideally be (1) called here
            %% in the MP_IDX_MANAGER constructor and (2) skipped if constructed
            %% from an existing object, neither of which work in Octave 5.2
            %% and earlier due to inheritance issues in constructors:
            %%   https://savannah.gnu.org/bugs/?52614
            %%
            %% WORKAROUND: In some subclass method(s), call INIT_SET_TYPES()
            %%             automatically as needed after construction, but
            %%             before use, checking first to ensure that it
            %%             hasn't already been called.
%             if isempty(obj.????)        %% skip if already initialized (e.g.
%                 obj.init_set_types();   %% constructed from existing object)
%             end
        end

        function obj = init_set_types(obj)
            %% base data struct for each type
            es = struct();
            ds = struct( ...
                'idx', struct( ...
                    'i1', es, ...
                    'iN', es, ...
                    'N', es ), ...
                'N', 0, ...
                'NS', 0, ...
                'order', struct( ...
                    'name', [], ...
                    'idx', [] ), ...
                'data', es );

            %% initialize each (set_type) field with base data structure
            for f = fieldnames(obj.set_types)'
                obj.(f{1}) = ds;
            end
        end

        function new_obj = copy(obj)
            %% make shallow copy of object
            new_obj = eval(class(obj));  %% create new object
            if have_feature('octave')
                s1 = warning('query', 'Octave:classdef-to-struct');
                warning('off', 'Octave:classdef-to-struct');
            end
            props = fieldnames(obj);
            if have_feature('octave')
                warning(s1.state, 'Octave:classdef-to-struct');
            end
            for k = 1:length(props)
                new_obj.(props{k}) = obj.(props{k});
            end
        end

        function display_set(obj, stype, sname)
            if nargin < 3
                sname = obj.set_types.(stype);
            end
            st = obj.(stype);    %% data for set type of interest
            if st.NS
                fmt = '%-26s %6s %8s %8s %8s\n';
                fprintf(fmt, sname, 'name', 'i1', 'iN', 'N');
                fprintf(fmt, repmat('=', 1, length(sname)), '------', '-----', '-----', '------');
                idx = st.idx;
                fmt = '%10d:%22s %8d %8d %8d\n';
                for k = 1:st.NS
                    name = st.order(k).name;
                    if isempty(st.order(k).idx)
                        fprintf(fmt, k, name, idx.i1.(name), idx.iN.(name), idx.N.(name));
                    else
                        vsidx = st.order(k).idx;
                        str = '%d'; for m = 2:length(vsidx), str = [str ',%d']; end
                        s = substruct('.', name, '()', vsidx);
                        nname = sprintf(['%s(' str, ')'], name, vsidx{:});
                        fprintf(fmt, k, nname, ...
                                subsref(idx.i1, s), subsref(idx.iN, s), subsref(idx.N, s));
                    end
                end
                fmt = sprintf('%%10d = %%s.NS%%%dd = %%s.N\\n\\n', 35-length(stype));
                fprintf(fmt, st.NS, stype, st.N, stype);
            else
                fprintf('%-26s  :  <none>\n', sname);
            end
        end

        obj = add_named_set(obj, set_type, name, idx, N, varargin)

        label = describe_idx(obj, set_type, idxs)

        varargout = get_idx(obj, varargin)

        rv = get_userdata(obj, name)

        val = get(obj, varargin)

        N = getN(obj, set_type, name, idx)

        obj = init_indexed_name(obj, set_type, name, dim_list)

        str = valid_named_set_type(obj, set_type)
    end     %% methods
end         %% classdef


%--- help for mdd/laplace_mcmc ---
%
%mdd/laplace_mcmc is a function.
%    log_mdd = laplace_mcmc(obj, ~, ~)
%