function [EEG com] = pop_selectmodel(EEG, model, type);

if nargin < 1
    help pop_selectmodel;
    return;
end;
com = '';

if ~isfield(EEG.etc,'amica') || isempty(EEG.etc.amica)
    error('No AMICA solution found. You should first load AMICA components');
end

guititle = 'Select/change data using AMICA model probabilities -- pop_selectmodel()';
data_options = 'Discard data for other models|Weight data by model probability';
if nargin < 2

    %newEEG = EEG;

    if EEG.etc.amica.num_models == 1
        error('Only one model exists');
    end

    % create user interface that allows choosing the model, weighting
    % method, selecting/discarding data.
    allmodels= 1:EEG.etc.amica.num_models;

    if ~isfield(EEG.etc.amica,'modnames')
        EEG.etc.amica.modnames{length(allmodels)} = '';
    end

    str = [num2str(allmodels(1)) fastif(~isempty(EEG.etc.amica.modnames{1}) ,[' - ' EEG.etc.amica.modnames{1}],'')];
    for i = 2:EEG.etc.amica.num_models
        str = [str '|' num2str(allmodels(i)) fastif(~isempty(EEG.etc.amica.modnames{i}) ,[' - ' EEG.etc.amica.modnames{i}],'')];
    end
    editwhat2select = str;

    %smooth_options = 'None (default)|Hann';
    cb_enable = ['set(findobj(''parent'', gcbf, ''tag'', ''labelstring'')    , ''enable'', ''on'');'];
    cb_disable = ['set(findobj(''parent'', gcbf, ''tag'', ''labelstring'')    , ''enable'', ''off'');'];
    cb_label = ['if get(gcbo,''value''),' cb_enable ...
        'else,' cb_disable ...
        'end;'];

    uilist = { {'style' 'text' 'string' 'Select model'} ...
        {'style' 'popupmenu' 'string' editwhat2select 'value' 1} ...
        {'style' 'text' 'string' 'Data selection/weighting'} ...
        {'style' 'popupmenu' 'string' data_options 'value' 1} ...
        {'style' 'checkbox' 'tag' 'labelcheck' 'string' 'Label the chosen model as:' 'value' 0 'callback' cb_label} ...
        {'style' 'edit' 'string' '' 'enable' 'off' 'tag' 'labelstring'}};

    uigeom = {[1 2] [1 2] [1 1]};

    result = inputgui(uigeom, uilist, 'pophelp(''pop_selectmodel'')', guititle, [], 'normal');

    if isempty(result)

        return
    end

    model = result{1};

    if result{3}
        if ~isfield(EEG.etc.amica,'modnames')
            for i = 1:EEG.etc.amica.num_models
                EEG.etc.amica.modnames{i} = '';
            end

        end
        EEG.etc.amica.modnames{model} = result{4};
    end

    type = result{2};
    EEG= selectmodel(EEG,model,type);

else
    if ischar(model) && isfield(EEG.etc.amica,'mod_names')
        for i = 1:EEG.etc.amica.num_models
            if strcmpi(model,EEG.etc.amica.mod_names{i})
                model = i;
                break;
            end
            model = 0;
        end
    end
    if model < 1
        error('Model not found');
    end
    if model>=EEG.etc.amica.num_models
        error('Model number exceeds the total number of models');
    end

    if nargin<3
        uilist = {{'style' 'text' 'string' 'Data selection/weighting'}...
                 {'style' 'popupmenu' 'string' data_options 'value' 1}};
        uigeom = {[1 1.5]};
        result = inputgui(uigeom, uilist, 'pophelp(''pop_selectmodel'')', guititle, [], 'normal');
        if isempty(result)
            return;
        end
        type = result{1};
    end
    EEG = selectmodel(EEG,model,type);
end

com = sprintf('%s = pop_selectmodel(%s,%d,%d)', inputname(1), inputname(1), model, type);


clc
clear all
close all

% To run this script we recommend running example2 first to create all the
% necessary outpouts from GLMsingle that are going to be reused here.

% This script shows how to save GLMsingle outputs as NIFTI files. NIFTI is
% neuroimaging format often used to store neuroimaging data. This script
% requires a NiFTi toolbox
% https://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image
% or alternatively one can use matlab's native support for nifti files
% (explaiend at the end of the script).

% load GLMsingle results
load('./example2outputs/GLMsingle/TYPED_FITHRF_GLMDENOISE_RR.mat')

% we will save following estiamtes (modelmd corresponds to single trial betas)
val2save = {'modelmd';'R2';'HRFindex';'FRACvalue'};
niftidir = './example2outputs/GLMsingle/GLMDENOISE_RR_nifti_files';
mkdir(niftidir);

voxelsize = [1.8 1.8 1.8];
origin = [0 0 0];

for v = 1 : length(val2save)

    nii = make_nii(eval(val2save{v}),voxelsize,origin);
    save_nii(nii,sprintf('%s/%s.nii',niftidir,val2save{v}))

end

% if you don't want to change the reference frame and position of the data
% (done by setting a new origin) you can reuse a NIFTI file (e.g T1 image)
% as a template for saving your results. This is usefull if your functional
% data is already aligned with the anatomy.

% template = load_nii('T1.nii')
% template is a matlab structure where "vol" field stores the data matrix.
% template.vol = eval(val2save{v}); swap the data to your GLMsingle output
% save_nii(template,sprintf('%s/%s.nii',niftidir,val2save{v})); save nifti

% additionally you can use matlab's native support for reading and saving
% nifti files (niftiread and niftiwrite). This skips making the nifti file
% and the header information can be directly added to niftiwrite function.
% info.Description = 'Modified using MATLAB R2017b';
% niftiwrite(nii,sprintf('%s/%s.nii',niftidir,val2save{v})), info);
% where info is a header.


function isargequalsize(x1,varargin)
%ISARGEQUALSIZE throws an error if not the same size
%
%   Usage: isargequalsize(x1,x2,...)
%
%   Input parameters:
%       x1,x2,...   - matrices to test
%
%   See also: isargequallength

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input  parameters ===================================
if nargin<2
    error('%s: you need at least two input arguments.',upper(mfilename));
end

%% ===== Checking for equal size =========================================
for ii = 1:nargin-1
    if ~isequal(size(varargin{ii}),size(x1))
        error('%s and %s have not the same size',inputname(1),inputname(ii+1));
    end
end


function s=get_name(a)

s=['bayesian model selection'];
eval_name                   %% print values of hyperparameters


% Pre-Processing of Code Generation with Simulink Data Object
% Make signal and parameter objects to define variable specifications (RAM/ROM)
% Resolve signal resolution with DISABLEIMPLICITSIGNALRESOLUTION

% make signal objects
sig.name = { ...
	'timer_en1_0', 'timer_en2_0', 'timer_pen_0', ...		% signals
	'operation_mode', 'motor_number', 'pen_idx', ...		% states (data store memories)
	'theta1m_ref_bl', 'theta2m_ref_bl', 'timer_trj', ...
	'ud_backlash1', 'ud_backlash2', ...						% states (unit delay blocks)
	'ud_engage1', 'ud_engage2', ...
	'ud_flag_enter', 'ud_flag_run', 'ud_flag_pen', ...
	'ud_theta1m_ref', 'ud_theta2m_ref' ...
	};
num_sig = length(sig.name);
for n = 1:num_sig
	cmd = strcat( ...
		sig.name{n}, ' = ', 'mpt.Signal;', ...
		sig.name{n}, '.RTWInfo.CustomAttributes.DefinitionFile = ''nxtscara_ram.c'';', ...
		sig.name{n}, '.RTWInfo.CustomAttributes.HeaderFile = ''nxtscara_ram.h'';' ...
		);
	eval(cmd)
end

% resolve signal resolution
sig.handle = disableimplicitsignalresolution(bdroot(gcb));

% make parameter objects
param.name = { ...
	'backlash1', 'backlash2', 'dthetam_bl', ...
	'engage1_iv', 'engage2_iv', 'num_mode', 'num_motor', ...
	'pwm1_adjst', 'pwm2_adjst', 'pwm3_adjst', 'pwm3_pen', ...
	'pwm1_gain', 'pwm1_offset', 'pwm2_gain', 'pwm2_offset', ...
	'theta1m_max', 'theta2m_max', 'theta1m_iv', 'theta2m_iv', ...
	'time_en1', 'time_en2', 'time_finish', ...
	'time_pwm3', 'time_pen', 'time_table_pen', 'time_wait', ...
	'x_ref', 'y_ref',  ...
	};
num_param = length(param.name);
param.value = cell(1, num_param);
for n = 1:num_param
	cmd = strcat( ...
		'param.value{', num2str(n), '} = ', param.name{n}, ';', ...
		param.name{n}, ' = ', 'mpt.Parameter;', ...
		param.name{n}, '.Value = ', 'param.value{', num2str(n), '};', ...
		param.name{n}, '.RTWInfo.CustomAttributes.DefinitionFile = ''nxtscara_rom.c'';', ...
		param.name{n}, '.RTWInfo.CustomAttributes.HeaderFile = ''nxtscara_rom.h'';' ...
		);
	eval(cmd)
end


classdef PTKEmphysemaImage < PTKPlugin
    % PTKEmphysemaImage. Plugin for computing the percentage of emphysema
    %     voxels
    %
    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using
    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.
    %     See PTKPlugin.m for more information on how to run plugins.
    %
    %     Plugins should not be run directly from your code.
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties
        ButtonText = 'Emphysema'
        ToolTip = 'Shows emphysema-like voxels'
        Category = 'Analysis'

        AllowResultsToBeCached = true
        AlwaysRunPlugin = false
        Context = PTKContextSet.LungROI
        PluginType = 'ReplaceOverlay'
        HidePluginInDisplay = false
        FlattenPreviewImage = true
        PTKVersion = '2'
        ButtonWidth = 6
        ButtonHeight = 1
        GeneratePreview = false
    end

    methods (Static)
        function emphysema_results_image = RunPlugin(dataset, context, reporting)
            roi = dataset.GetResult('PTKLungROI');
            context_no_airways = dataset.GetResult('PTKGetMaskForContextExcludingAirways', context);
            roi.ResizeToMatch(context_no_airways);
            [~, emphysema_results_image] = PTKComputeEmphysemaFromMask(roi, context_no_airways);
            emphysema_results_image.ImageType = PTKImageType.Colormap;
        end
    end
end


%This is the Matlab interface to the OMP2 MEX implementation.
%The function is not for independent use, only through omp2.m.

%OMP2MEX Matlab interface to the OMP2 MEX implementation.
%  GAMMA = OMP2MEX(D,X,DtX,XtX,G,EPSILON,SPARSE_G,MSGDELTA,MAXATOMS,PROFILE)
%  invokes the OMP2 MEX function according to the specified parameters. Not
%  all the parameters are required. Those among D, X, DtX, XtX and G which
%  are not specified should be passed as [].
%
%  EPSILON - the target error.
%  SPARSE_G - returns a sparse GAMMA when nonzero, full GAMMA when zero.
%  MSGDELTA - the delay in secs between messages. Zero means no messages.
%  MAXATOMS - the max number of atoms per signal, negative for no max.
%  PROFILE - nonzero means that profiling information should be printed.

%  Ron Rubinstein
%  Computer Science Department
%  Technion, Haifa 32000 Israel
%  ronrubin@cs
%
%  April 2009


function dim = getDimension(~)
%GETDIMENSION   Returns 3 for a SPINOP3.
%
% See also SPINOP3.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

dim = 3;

end


function inspect_bug1230

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

% this is not really pertaining to a bug, but to a feature request.

load(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg/preproc_ctf151.mat'));

cfg = [];
cfg.method = 'summary';
cfg.layout = 'CTF151.lay';
data = ft_rejectvisual(cfg, data);


function varargout = drawEdge(varargin)
%DRAWEDGE Draw an edge given by 2 points
%
%   drawEdge(x1, y1, x2, y2);
%   draw an edge between the points (x1 y1) and  (x2 y2).
%
%   drawEdge([x1 y1 x2 y2]) ;
%   drawEdge([x1 y1], [x2 y2]);
%   specify data either as bundled edge, or as 2 points
%
%   The function supports 3D edges:
%   drawEdge([x1 y1 z1 x2 y2 z2]);
%   drawEdge([x1 y1 z1], [x2 y2 z2]);
%   drawEdge(x1, y1, z1, x2, y2, z2);
%
%   Arguments can be single values or array of size [N*1]. In this case,
%   the function draws multiple edges.
%
%   H = drawEdge(..., OPT), with OPT being a set of pairwise options, can
%   specify color, line width and so on...
%
%   H = drawEdge(...) return handle(s) to created edges(s)
%
%   See also:
%   edges2d, drawCenteredEdge, drawLine
%
%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 31/10/2003.
%

%   HISTORY
%   19/02/2004 add support for arrays of edges.
%   31/03/2004 change format of edges to [P1 P2] and variants.
%   28/11/2004 add support for 3D edges
%   01/08/2005 add support for drawing options
%   31/05/2007 update doc, and code makeup
%   03/08/2010 re-organize code

% separate edge and optional arguments
[ax, edge, options] = parseInputArguments(varargin{:});

% draw the edges
if size(edge, 2) == 4
    h = drawEdge_2d(ax, edge, options);
else
    h = drawEdge_3d(ax, edge, options);
end

% eventually return handle to created edges
if nargout > 0
    varargout = {h};
end

function h = drawEdge_2d(ax, edge, options)

h = -1 * ones(size(edge, 1), 1);

for i = 1:size(edge, 1)
    if isnan(edge(i,1))
        continue;
    end

    h(i) = plot(ax, edge(i, [1 3]), edge(i, [2 4]), options{:});
end

function h = drawEdge_3d(ax, edge, options)

h = -1 * ones(size(edge, 1), 1);

for i = 1:size(edge, 1)
    if isnan(edge(i,1))
        continue;
    end

    h(i) = plot3(ax, edge(i, [1 4]), edge(i, [2 5]), edge(i, [3 6]), options{:});
end

function [ax, edge, options] = parseInputArguments(varargin)

% extract handle of axis to draw on
if isAxisHandle(varargin{1})
    ax = varargin{1};
    varargin(1) = [];
else
    ax = gca;
end

% find the number of arguments defining edges
nbVal = 0;
for i = 1:length(varargin)
    if isnumeric(varargin{i})
        nbVal = nbVal+1;
    else
        % stop at the first non-numeric value
        break;
    end
end

% extract drawing options
options = varargin(nbVal+1:end);

% ensure drawing options have correct format
if length(options) == 1
    options = [{'color'}, options];
end

% extract edges characteristics
switch nbVal
    case 1
        % all parameters in a single array
        edge = varargin{1};

    case 2
        % parameters are two points, or two arrays of points, of size N*2.
        p1 = varargin{1};
        p2 = varargin{2};
        edge = [p1 p2];

    case 4
        % parameters are 4 parameters of the edge : x1 y1 x2 and y2
        edge = [varargin{1} varargin{2} varargin{3} varargin{4}];

    case 6
        % parameters are 6 parameters of the edge : x1 y1 z1 x2 y2 and z2
        edge = [varargin{1} varargin{2} varargin{3} varargin{4} varargin{5} varargin{6}];

    otherwise
        error('drawEdge:WrongNumberOfParameters', 'Wrong number of parameters');
end


function hole_num = p14_hole_num ( )

%*****************************************************************************80
%
%% P14_HOLE_NUM counts the holes in problem 14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer HOLE_NUM, the number of holes.
%
  hole_num = 1;

  return
end


function test_bug2385

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_filetype ft_read_sens

cd(dccnpath('/home/common/matlab/fieldtrip/data/test/original/electrodes/easycap'));

filename = {
  'M10_ThetaPhi.txt'
  'M1_ThetaPhi.txt'
  'M1_XYZ.txt'
  };

for i=1:length(filename)
  assert(ft_filetype(filename{i}, 'easycap_txt'));
  elec = ft_read_sens(filename{i});
  figure
  ft_plot_sens(elec);
end


function [TableHHStats] = getBasicHarveyStats(male,female)
% This function compiles basic statistics on the male and female whole-body
% metabolic model
%
% function [TableHHStats] = getBasicHarveyStats(male,female)
%
% INPUT
% male          Model structure containing the male model
% female        Model structure containing the female model
%
% OUTPUT
% TableHHStats  Table containing the statistics
%
% Ines Thiele 2016- 2019

% build table
clear TableHHStats
c = 1;

SL = (find(~cellfun(@isempty,strfind(female.mets,'slack_'))));
SL_female = SL;
SL = (find(~cellfun(@isempty,strfind(male.mets,'slack_'))));
SL_male = SL;

TableHHStats{c , 1} = '';
TableHHStats{c , 2} = 'Harvetta';
TableHHStats{c , 3} = 'Harvey'; c = c+1;

TableHHStats{c , 1} = 'Number of Reactions';

TableHHStats{c , 2} = num2str(length(female.rxns));
TableHHStats{c , 3} = num2str(length(male.rxns)); c = c+1;

TableHHStats{c , 1} = 'Number of Metabolites';

TableHHStats{c , 2} = num2str(length(female.mets)-length(SL_female));
TableHHStats{c , 3} = num2str(length(male.mets)-length(SL_male)); c = c+1;

TableHHStats{c , 1} = 'Number of Genes (transcripts)';
TableHHStats{c , 2} = num2str(length(female.genes));
TableHHStats{c , 3} = num2str(length(male.genes)); c = c+1;

TableHHStats{c , 1} = 'Number of Genes (unique)';
[a,b]=strtok(female.genes,'.');

TableHHStats{c , 2} = num2str(length(unique(a)));
[a,b]=strtok(male.genes,'.');
TableHHStats{c , 3} = num2str(length(unique(a))); c = c+1;

TableHHStats{c , 1} = 'Number of Subsystems';

% Feb 2020, moved this to loadPSCMfile
% Oct 2017 % clean up final remaining subsystem names
% female.subSystems(strmatch('Transport, endoplasmic reticular',female.subSystems,'exact'))={'Transport, endoplasmic reticulum'};
% female.subSystems(strmatch('Arginine and Proline Metabolism',female.subSystems,'exact'))={'Arginine and proline Metabolism'};
% female.subSystems(strmatch(' ',female.subSystems,'exact'))={'Miscellaneous'};
%
% male.subSystems(strmatch('Transport, endoplasmic reticular',male.subSystems,'exact'))={'Transport, endoplasmic reticulum'};
% male.subSystems(strmatch('Arginine and Proline Metabolism',male.subSystems,'exact'))={'Arginine and proline Metabolism'};
% male.subSystems(strmatch(' ',male.subSystems,'exact'))={'Miscellaneous'};

TableHHStats{c , 2} = num2str(length(unique(female.subSystems))-1);%do not count dummy reactions
TableHHStats{c , 3} = num2str(length(unique(male.subSystems))-1); c = c+1;%do not count dummy reactions

TableHHStats{c , 1} = 'Blood compartment metabolites';
BC_mets = (find(~cellfun(@isempty,strfind(female.mets,'[bc]'))));
SL_female = (find(~cellfun(@isempty,strfind(female.mets,'slack_'))));
BC_mets_female = setdiff(BC_mets,SL_female);

BC_mets = (find(~cellfun(@isempty,strfind(male.mets,'[bc]'))));
SL_male = (find(~cellfun(@isempty,strfind(male.mets,'slack_'))));
BC_mets_male = setdiff(BC_mets,SL_male);

TableHHStats{c , 2} = num2str(length(BC_mets_female));
TableHHStats{c , 3} = num2str(length(BC_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Urine metabolites';
U_mets = (find(~cellfun(@isempty,strfind(female.mets,'[u]'))));
U_mets_female = setdiff(U_mets,SL_female);

U_mets = (find(~cellfun(@isempty,strfind(male.mets,'[u]'))));
U_mets_male = setdiff(U_mets,SL_male);

TableHHStats{c , 2} = num2str(length(U_mets_female));
TableHHStats{c , 3} = num2str(length(U_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Portal vein metabolites';
BP_mets = (find(~cellfun(@isempty,strfind(female.mets,'[bp]'))));
BP_mets_female = setdiff(BP_mets,SL_female);

BP_mets = (find(~cellfun(@isempty,strfind(male.mets,'[bp]'))));
BP_mets_male = setdiff(BP_mets,SL_male);

TableHHStats{c , 2} = num2str(length(BP_mets_female));
TableHHStats{c , 3} = num2str(length(BP_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Bile duct metabolites';

BD_mets = (find(~cellfun(@isempty,strfind(female.mets,'[bd]'))));
BD_mets_female = setdiff(BD_mets,SL_female);

BD_mets = (find(~cellfun(@isempty,strfind(male.mets,'[bd]'))));
BD_mets_male = setdiff(BD_mets,SL_male);

TableHHStats{c , 2} = num2str(length(BD_mets_female));
TableHHStats{c , 3} = num2str(length(BD_mets_male)); c = c+1;

TableHHStats{c , 1} = 'CSF metabolites';

CSF_mets = (find(~cellfun(@isempty,strfind(female.mets,'[csf]'))));
CSF_mets_female = setdiff(CSF_mets,SL_female);

CSF_mets = (find(~cellfun(@isempty,strfind(male.mets,'[csf]'))));
CSF_mets_male = setdiff(CSF_mets,SL_male);

TableHHStats{c , 2} = num2str(length(CSF_mets_female));
TableHHStats{c , 3} = num2str(length(CSF_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Diet metabolites';

D_mets = (find(~cellfun(@isempty,strfind(female.mets,'[d]'))));
D_mets_female = setdiff(D_mets,SL_female);
D_mets = (find(~cellfun(@isempty,strfind(male.mets,'[d]'))));
D_mets_male = setdiff(D_mets,SL_male);

TableHHStats{c , 2} = num2str(length(D_mets_female));
TableHHStats{c , 3} = num2str(length(D_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Fecal metabolites';

Fe_mets = (find(~cellfun(@isempty,strfind(female.mets,'[fe]'))));
Fe_mets_female = setdiff(Fe_mets,SL_female);

Fe_mets = (find(~cellfun(@isempty,strfind(male.mets,'[fe]'))));
Fe_mets_male = setdiff(Fe_mets,SL_male);

TableHHStats{c , 2} = num2str(length(Fe_mets_female));
TableHHStats{c , 3} = num2str(length(Fe_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Sweat metabolites';

Fe_mets = (find(~cellfun(@isempty,strfind(female.mets,'[sw]'))));
Fe_mets_female = setdiff(Fe_mets,SL_female);

Fe_mets = (find(~cellfun(@isempty,strfind(male.mets,'[sw]'))));
Fe_mets_male = setdiff(Fe_mets,SL_male);

TableHHStats{c , 2} = num2str(length(Fe_mets_female));
TableHHStats{c , 3} = num2str(length(Fe_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Air metabolites';

A_mets = (find(~cellfun(@isempty,strfind(female.mets,'[a]'))));
A_mets_female = setdiff(A_mets,SL_female);

A_mets = (find(~cellfun(@isempty,strfind(male.mets,'[a]'))));
A_mets_male = setdiff(A_mets,SL_male);

TableHHStats{c , 2} = num2str(length(A_mets_female));
TableHHStats{c , 3} = num2str(length(A_mets_male)); c = c+1;

TableHHStats{c , 1} = 'Milk metabolites';

Fe_mets = (find(~cellfun(@isempty,strfind(female.mets,'[mi]'))));
Fe_mets_female = setdiff(Fe_mets,SL_female);

Fe_mets = (find(~cellfun(@isempty,strfind(male.mets,'[mi]'))));
Fe_mets_male = setdiff(Fe_mets,SL_male);

TableHHStats{c , 2} = num2str(length(Fe_mets_female));
TableHHStats{c , 3} = num2str(length(Fe_mets_male)); c = c+1;


function res = ctranspose(obj,useconj);
    if nargin == 1
        useconj = 1;
    end

    if length(obj.dimensions) > 2
        error('Cannot transpose array');
    end

    % make new memory mapped data file
    % --------------------------------
    newFileName = mmo.getnewfilename;
    copyfile(obj.dataFile, newFileName);

    res = obj;
    res.dimensions = [ obj.dimensions(2) obj.dimensions(1) ];
    res.dataFile = newFileName;
    tmpMMO1 = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
    tmpMMO2 = memmapfile(res.dataFile, 'writable',         true, 'format', { 'single' res.dimensions 'x' });

    % copy the data
    % -------------
    if length(obj.dimensions) == 1 || obj.dimensions(1) > obj.dimensions(2)
        for index = 1:size(obj,2)
            s.type = '()';
            s.subs = { ':' index };
            if useconj, tmpMMO2.Data.x(index,:) = conj(subsref(tmpMMO1.Data.x,s));
            else        tmpMMO2.Data.x(:,index) =      subsref(tmpMMO1.Data.x,s);
            end
        end
    else
        for index = 1:size(obj,1)
            s.type = '()';
            s.subs = { index ':' };
            if useconj, tmpMMO2.Data.x(:,index) = conj(subsref(tmpMMO1.Data.x,s));
            else        tmpMMO2.Data.x(:,index) =      subsref(tmpMMO1.Data.x,s);
            end
        end
    end


function [y,newp,retcode]=ssfile(obj,y,p,d,id) %#ok<INUSL>

% risessfile --  computes the steady state of ... analytically
%
% ::
%
%
%   [y,newp,retcode]=risessfile(obj,y,p,d,id)
%
% Args:
%
%    - **obj** [rise|dsge]: model object (not always needed)
%
%    - **y** [vector]: endo_nbr x 1 vector of initial steady state
%
%    - **p** [struct]: parameter structure
%
%    - **d** [struct]: definitions
%
%    - **id** [vector]: location of the variables to calculate
%
% Returns:
%    :
%
%    - **y** []: endo_nbr x 1 vector of updated steady state
%
%    - **newp** [struct]: structure containing updated parameters if any
%
%    - **retcode** [0|number]: return 0 if there are no problems, else return
%      any number different from 0
%
% Note:
%
%    - this is new approach has three main advantages relative to the previous
%      one:
%      - The file is valid whether we have many regimes or not
%      - The user does not need to know what regime is being computed
%      - It is in sync with the steady state model
%
% Example:
%
%    See also:

% Conversion of Dynare file [Dynare_edo_steadystate.m] into RISE file [risessfile.m]
%
%  Done 23-Jul-2017 00:31:15.

retcode=0;

if nargin==1
    % list of endogenous variables to be calculated
    %----------------------------------------------
    % y=get(obj,'endo_list');
    y={'RC','RK','WC','WK','YC','YK','MCC','MCK','KC','KK','PKB','R','L','QK',...
        'HC','HSC','HK','HSK','UHC','UHSC','UHK','UHSK','empC','HrC',...
        'empK','HrK','empSC','HrSC','empSK','HrSK','unemp','EIK','EC','INFWC',...
        'INFWK','INFC','INFK','DIFFNORMGDP','NORMINFGDP','DIFFREALGDP',...
        'DIFFREALEC','DIFFREALEIK','DIFFREALW','AH','INFGDP','INFCNA','INFCOR',...
        'GAP','PFGAP','INFC10','ECD','KD','RCD','QCD','KCH','RCH','ECH','QCH',...
        'LAGKD','LAGKCH','UK','UC','DIFFREALECH','DIFFREALECD','betas','XiL',...
        'Lpref','EFFK','MUZK','MUZM','HG','MUC','MUK','EFFECD','EFFECH','STAR',...
        'RL1','RL2','RL3','RL4','RL5','RL6','RL7','RT2','DIFFREALGDP_obs',...
        'DIFFREALEC_obs','DIFFREALEIK_obs','DIFFREALECD_obs','DIFFREALECH_obs',...
        'DIFFREALW_obs','AH_obs','INFCNA_obs','INFCOR_obs','INFK_obs','R_obs',...
        'RT2_obs','unemp_obs'};
    % list of parameters to be computed during steady state calculation
    %-------------------------------------------------------------------
    newp={'AA','AHSS','A_HC','A_HK','DD','DIFFREALECDSS','DIFFREALECDSS_obs',...
        'DIFFREALECHSS','DIFFREALECHSS_obs','DIFFREALECSS','DIFFREALECSS_obs',...
        'DIFFREALEIKSS','DIFFREALEIKSS_obs','DIFFREALGDPSS','DIFFREALGDPSS_obs',...
        'DIFFREALWSS','DIFFREALWSS_obs','ECDSS','ECHSS','ECSS','EIKSS','HCSS',...
        'HKSS','HSCSS','HSKSS','HSS','HrCSS','HrKSS','HrSCSS','HrSKSS',...
        'IMPHSSS','INFC10SS','INFCNASS','INFCNASS_obs','INFCORSS','INFCORSS_obs',...
        'INFCSS','INFGDPSS','INFKSS','INFKSS_obs','INFWCSS','INFWKSS','KCDSS',...
        'KCHSS','KCSS','KKSS','LSS','MCCSS','MCKSS','MUCSS','MUCSShabit','MUKSS',...
        'MUKSShabit','MUZCSS','ONE','PKBSS','PYSS','QCDSS','QCHSS','QKSS',...
        'RCDSS','RCHSS','RCSS','RKSS','RL1SS','RL2SS','RL3SS','RL4SS','RL5SS',...
        'RL6SS','RL7SS','RR','RSS','RSS_obs','RT2SS','RT2SS_obs','Rnr','UCSS',...
        'UHCSS','UHKSS','UHSCSS','UHSKSS','UKSS','USS','WCSS','WKSS','YCSS',...
        'YKSS','YYSS','beta_','beta_0','beta_2','empCSS','empKSS','empSCSS',...
        'empSKSS','eta_cd','eta_cd_eta_cnn','eta_ch','eta_ch_eta_cnn','eta_cnn',...
        'hc_hk','mu_','s_c_ech','s_ecdc','s_k','s_k_ecd','s_k_eik','s_yc',...
        'theta_wc','theta_wk','unempSS','unempSS_obs','xsi_HrC','xsi_HrK',...
        'xsi_NC','xsi_NK','ycbi','ycbi_ykb','ykb'};
else

    newp=struct();

    %start_steady_state;

    newp.beta_0 = p.pbeta;
    newp.beta_2 = p.pbeta*p.rpr; % s.s. funds rate premium
    newp.beta_ = newp.beta_2;
    newp.MUZCSS=1;
    newp.ONE=1;
    newp.USS=1;
    newp.MUKSS=p.MUZKSS*p.MUZMSS;
    newp.MUCSS=p.MUZKSS^p.alpha_*p.MUZMSS;
    newp.MUKSShabit=newp.MUKSS;
    newp.MUCSShabit=newp.MUCSS;
    newp.PKBSS=p.theta_k/(p.theta_k-1)*(p.theta_c-1)/p.theta_c;
    newp.PYSS=1;
    newp.MCCSS=(p.theta_c-1)/p.theta_c;
    newp.MCKSS=(p.theta_k-1)/p.theta_k;
    newp.RKSS=newp.MUKSS/newp.beta_2-(1-p.delta_);
    newp.RCSS=newp.MUKSS/newp.beta_2-(1-p.delta_);
    newp.RCHSS=newp.MUCSS/newp.beta_2-(1-p.delta_ch); % Housing sector
    newp.RCDSS=newp.MUKSS/newp.beta_2-(1-p.delta_cd); % Durable sector
    newp.USS=1;
    newp.mu_=newp.RCSS;
    newp.AA=p.alpha_/newp.RKSS*newp.MCKSS;
    newp.DD = 0.135;
    newp.RR = 0.075;
    newp.eta_cnn=1;
    newp.eta_cd_eta_cnn=newp.DD/((newp.MUKSShabit-newp.beta_2*p.h_cd)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_cd/newp.MUKSShabit)*(1-(1-p.delta_cd)/newp.MUKSS)/newp.RCDSS);
    newp.eta_ch_eta_cnn=newp.RR/((newp.MUCSShabit-newp.beta_2*p.h_ch)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_ch/newp.MUCSShabit)*(1-(1-p.delta_ch)/newp.MUCSS)/newp.RCHSS);
    newp.eta_ch=newp.eta_ch_eta_cnn;
    newp.eta_cd=newp.eta_cd_eta_cnn;
    newp.DD=newp.eta_cd_eta_cnn*(newp.MUKSShabit-newp.beta_2*p.h_cd)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_cd/newp.MUKSShabit)*(1-(1-p.delta_cd)/newp.MUKSS)/newp.RCDSS;
    newp.RR=newp.eta_ch_eta_cnn*(newp.MUCSShabit-newp.beta_2*p.h_ch)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_ch/newp.MUCSShabit)*(1-(1-p.delta_ch)/newp.MUCSS)/newp.RCHSS;
    newp.Rnr=(1-(1-p.delta_)/newp.MUKSS)*newp.AA*newp.MUKSS;
    newp.ycbi_ykb=((1-p.s_AS)-newp.Rnr)/((newp.DD*(1-p.s_AS)/(1+newp.RR))+newp.Rnr);
    newp.hc_hk=newp.ycbi_ykb*(newp.RCSS*newp.MCKSS/(newp.RKSS*newp.MCCSS))^(p.alpha_/(1-p.alpha_));
    newp.HSS=0.25;
    newp.AHSS=newp.HSS;
    newp.HKSS=newp.HSS/(1+newp.hc_hk);
    newp.HCSS=newp.HSS-newp.HKSS;
    newp.HrCSS=1/3;
    newp.HrKSS=1/3;
    newp.empCSS=newp.HCSS/newp.HrCSS;
    newp.empKSS=newp.HKSS/newp.HrKSS;
    newp.ycbi=newp.HCSS*(newp.AA)^(p.alpha_/(1-p.alpha_));
    newp.ykb=newp.HKSS*(newp.AA)^(p.alpha_/(1-p.alpha_));
    newp.YCSS=newp.ycbi;
    newp.YKSS=newp.ykb;
    newp.KCSS=newp.AA*newp.ycbi*newp.MUKSS;
    newp.KKSS=newp.AA*newp.ykb*newp.MUKSS;
    newp.ECHSS=newp.RR/(1+newp.RR)*newp.ycbi*(1-p.s_AS);
    newp.ECSS=1/(1+newp.RR)*newp.ycbi*(1-p.s_AS);
    newp.ECDSS=newp.DD*newp.PKBSS*newp.ECSS;
    newp.EIKSS=(1-(1-p.delta_)/newp.MUKSS)*(newp.KCSS+newp.KKSS);
    newp.KCDSS=newp.ECDSS/(1-(1-p.delta_cd)/newp.MUKSS);
    newp.KCHSS=newp.ECHSS/(1-(1-p.delta_ch)/newp.MUCSS);
    newp.YYSS=(newp.YCSS+newp.YKSS*newp.PKBSS)/newp.PYSS;
    newp.s_k_ecd=newp.ECDSS/newp.YKSS;
    newp.s_c_ech=newp.ECHSS/newp.YCSS;
    newp.s_k_eik=newp.EIKSS/newp.YKSS;
    newp.s_yc = (newp.YCSS/newp.YYSS);
    newp.s_ecdc=newp.PKBSS*newp.ECDSS/(newp.ECSS+newp.PKBSS*newp.ECDSS+(newp.MUCSS/newp.beta_2-1+p.delta_ch)*newp.KCHSS);
    newp.INFCNASS=exp(.02/4);
    newp.INFCSS = newp.INFCNASS*((newp.MUZCSS/p.MUZKSS)^(1-p.alpha_))^(-newp.s_ecdc);
    newp.INFCORSS=newp.INFCNASS;
    newp.INFKSS=newp.INFCSS*(newp.MUZCSS/p.MUZKSS)^(1-p.alpha_);
    newp.INFWCSS=newp.INFCSS*p.MUZKSS^p.alpha_*p.MUZMSS;
    newp.INFWKSS=newp.INFWCSS;
    newp.RSS=newp.INFCSS/newp.beta_0*newp.MUCSS;
    newp.RT2SS=exp(p.tp2)*newp.RSS;
    newp.INFC10SS = newp.INFCNASS;
    newp.IMPHSSS = newp.RCHSS*newp.KCHSS;
    newp.s_k=newp.PKBSS*newp.YKSS/newp.YYSS;
    newp.INFGDPSS=newp.INFCSS^(newp.YCSS/newp.YYSS)*newp.INFKSS^(newp.YKSS*newp.PKBSS/(newp.YYSS));
    newp.LSS=newp.eta_cnn/(newp.ECSS*(1-p.h/newp.MUCSShabit))-newp.eta_cnn*newp.beta_2*p.h/(newp.ECSS*(newp.MUCSShabit-p.h));
    newp.WCSS=newp.MCCSS*(1-p.alpha_)*newp.YCSS/newp.HCSS;
    newp.WKSS=newp.MCKSS*(1-p.alpha_)*newp.YKSS/newp.HKSS;
    % xsiN_xsiH_C = ((newp.HrCSS/newp.empCSS)^(1+p.sigmah))/(1+1/p.sigmah);
    % xsiN_xsiH_K = ((newp.HrKSS/newp.empKSS)^(1+p.sigmah))/(1+1/p.sigmah);
    % gC = (1/(1+p.sigman) + 1/p.sigmah)*(xsiN_xsiH_C*(1+p.sigmah)/p.sigmah)^(-(1+p.sigman)/(1+p.sigman+p.sigmah));
    % markup_xsiN_C = (newp.HCSS^((1+p.sigmah)*(1+p.sigman)/(1+p.sigmah+p.sigman)-1))*gC/(newp.LSS*newp.WCSS);
    % gK = (1/(1+p.sigman) + 1/p.sigmah)*(xsiN_xsiH_K*(1+p.sigmah)/p.sigmah)^(-(1+p.sigman)/(1+p.sigman+p.sigmah));
    % markup_xsiN_K = (newp.HKSS^((1+p.sigmah)*(1+p.sigman)/(1+p.sigmah+p.sigman)-1))*gK/(newp.LSS*newp.WKSS);
    % markup_w = (1-newp.unempSS)^((1+p.sigmah+p.sigman)/(1+p.sigmah) - 1 - p.sigman);
    markup_w = (1-p.unempSS)^((1+p.sigmah+p.sigman)/(1+p.sigmah) - 1 - p.sigman);
    newp.theta_wc = markup_w/(markup_w -1); newp.theta_wk = newp.theta_wc;
    newp.A_HC=newp.LSS*(newp.theta_wc-1)/newp.theta_wc*newp.WCSS/(((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));
    newp.A_HK=newp.LSS*(newp.theta_wk-1)/newp.theta_wk*newp.WKSS/(((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));
    newp.xsi_NC=newp.A_HC/((1/(1+p.sigman)+1/p.sigmah)*(newp.HCSS^p.sigman/newp.HrCSS^(1+p.sigman+p.sigmah))^((1+p.sigman)/(1+p.sigman+p.sigmah)));
    newp.xsi_NK=newp.A_HK/((1/(1+p.sigman)+1/p.sigmah)*(newp.HKSS^p.sigman/newp.HrKSS^(1+p.sigman+p.sigmah))^((1+p.sigman)/(1+p.sigman+p.sigmah)));
    newp.xsi_HrC=newp.xsi_NC*(1+p.sigmah)/p.sigmah*(newp.HCSS^p.sigman/newp.HrCSS^(1+p.sigman+p.sigmah));
    newp.xsi_HrK=newp.xsi_NK*(1+p.sigmah)/p.sigmah*(newp.HKSS^p.sigman/newp.HrKSS^(1+p.sigman+p.sigmah));
    newp.UHCSS=newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;
    newp.UHKSS=newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;
    newp.HSCSS=(newp.WCSS*newp.LSS/(newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))))^(1/(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));
    newp.HSKSS=(newp.WKSS*newp.LSS/(newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))))^(1/(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));
    newp.empSCSS=((1+p.sigmah)/p.sigmah*newp.xsi_NC/newp.xsi_HrC)^(-1/(1+p.sigmah+p.sigman))*newp.HSCSS^(1/(1+p.sigman/(1+p.sigmah)));
    newp.empSKSS=((1+p.sigmah)/p.sigmah*newp.xsi_NK/newp.xsi_HrK)^(-1/(1+p.sigmah+p.sigman))*newp.HSKSS^(1/(1+p.sigman/(1+p.sigmah)));
    newp.HrSCSS=newp.HSCSS/newp.empSCSS;
    newp.HrSKSS=newp.HSKSS/newp.empSKSS;
    newp.UHSCSS=newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HSCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;
    newp.UHSKSS=newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HSKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;
    newp.unempSS=(newp.empSCSS+newp.empSKSS-(newp.empCSS+newp.empKSS))/(newp.empSCSS+newp.empSKSS);
    newp.QKSS=1;
    newp.QCDSS=1;
    newp.QCHSS=1;
    newp.UCSS=1;
    newp.UKSS=1;
    % XiBSS=1;
    % XiDSS=1;
    % XiHSS=1;
    newp.RL1SS=newp.RSS;
    newp.RL2SS=newp.RSS;
    newp.RL3SS=newp.RSS;
    newp.RL4SS=newp.RSS;
    newp.RL5SS=newp.RSS;
    newp.RL6SS=newp.RSS;
    newp.RL7SS=newp.RSS;
    newp.DIFFREALECSS =exp( log(newp.MUCSS));
    newp.DIFFREALEIKSS =exp( log(newp.MUKSS));
    newp.DIFFREALECDSS =exp( log(newp.MUKSS));
    newp.DIFFREALECHSS =exp( log(newp.MUCSS));
    newp.DIFFREALWSS =exp( log(newp.MUCSS) );
    newp.DIFFREALGDPSS =exp( (1-newp.s_k)*log(newp.MUCSS)+(newp.s_k)*log(newp.MUKSS));

    %end_steady_state;

    %trends;

    newp.DIFFREALGDPSS_obs=(1-newp.s_k)*log(newp.MUCSS)*100+(newp.s_k)*log(newp.MUKSS)*100;
    newp.DIFFREALECSS_obs=log(newp.MUCSS)*100;
    newp.DIFFREALEIKSS_obs=log(newp.MUKSS)*100;
    newp.DIFFREALECDSS_obs=log(newp.MUKSS)*100;
    newp.DIFFREALECHSS_obs=log(newp.MUCSS)*100;
    newp.DIFFREALWSS_obs=log(newp.MUCSS)*100;
    newp.INFCNASS_obs=(1-newp.s_ecdc)*log(newp.INFCSS)*100+newp.s_ecdc*log(newp.INFKSS)*100;
    newp.INFCORSS_obs=(1-newp.s_ecdc)*log(newp.INFCSS)*100+newp.s_ecdc*log(newp.INFKSS)*100;
    newp.INFKSS_obs=log(newp.INFCSS)*100-log(newp.MUKSS)*100+log(newp.MUCSS)*100;
    newp.RSS_obs=log(newp.RSS)*100;
    newp.RT2SS_obs=log(newp.RT2SS)*100;
    newp.unempSS_obs=100*log(newp.unempSS);

    %end_trends;

    ys = [
        newp.RCSS
        newp.RKSS
        newp.WCSS
        newp.WKSS
        newp.YCSS
        newp.YKSS
        newp.MCCSS
        newp.MCKSS
        newp.KCSS
        newp.KKSS
        newp.PKBSS
        newp.RSS
        newp.LSS
        newp.QKSS
        newp.HCSS
        newp.HSCSS
        newp.HKSS
        newp.HSKSS
        newp.UHCSS
        newp.UHSCSS
        newp.UHKSS
        newp.UHSKSS
        newp.empCSS
        newp.HrCSS
        newp.empKSS
        newp.HrKSS
        newp.empSCSS
        newp.HrSCSS
        newp.empSKSS
        newp.HrSKSS
        newp.unempSS
        newp.EIKSS
        newp.ECSS
        newp.INFWCSS
        newp.INFWKSS
        newp.INFCSS
        newp.INFKSS
        newp.ONE
        newp.ONE
        newp.DIFFREALGDPSS
        newp.DIFFREALECSS
        newp.DIFFREALEIKSS
        newp.DIFFREALWSS
        newp.AHSS
        newp.INFGDPSS
        newp.INFCNASS
        newp.INFCORSS
        newp.ONE
        newp.ONE
        newp.INFC10SS
        newp.ECDSS
        newp.KCDSS
        newp.RCDSS
        newp.QCDSS
        newp.KCHSS
        newp.RCHSS
        newp.ECHSS
        newp.QCHSS
        newp.KCDSS
        newp.KCHSS
        newp.USS
        newp.USS
        newp.DIFFREALECHSS
        newp.DIFFREALECDSS
        newp.beta_
        newp.ONE
        newp.ONE
        newp.ONE
        p.MUZKSS
        p.MUZMSS
        newp.ONE
        newp.MUCSS
        newp.MUKSS
        newp.ONE
        newp.ONE
        newp.ONE
        newp.RL1SS
        newp.RL2SS
        newp.RL3SS
        newp.RL4SS
        newp.RL5SS
        newp.RL6SS
        newp.RL7SS
        newp.RT2SS
        newp.DIFFREALGDPSS_obs
        newp.DIFFREALECSS_obs
        newp.DIFFREALEIKSS_obs
        newp.DIFFREALECDSS_obs
        newp.DIFFREALECHSS_obs
        newp.DIFFREALWSS_obs
        newp.ONE
        newp.INFCNASS_obs
        newp.INFCORSS_obs
        newp.INFKSS_obs
        newp.RSS_obs
        newp.RT2SS_obs
        newp.unempSS_obs
        ];

    y(id)=ys;

end

end


function pbma_write_test ( file_out_name )

%*****************************************************************************80
%
%% PBMA_WRITE_TEST tests the ASCII portable bit map write routines.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 August 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character *file_out_name, the name of the file
%    to contain the ASCII portable pixel map data.
%
  nrow = 200;
  ncol = 200;
%
%  Set the data.
%
  b = pbma_example ( nrow, ncol );
%
%  Write the data to the file.
%
  pbma_write ( file_out_name, b );

  return
end


function options = ppcaOptions(mappingType, latentPoints, mappingOptions)

% PPCAOPTIONS Options for probabilistic PCA.
% FORMAT
% DESC returns the default options for probabilistic PCA.
% RETURN options : default options structure for probabilistic PCA.
%
%
% SEEALSO : ppcaCreate
%
% COPYRIGHT : Neil D. Lawrence, 2008

% MLTOOLS

options = [];


function success = createMhaMask(scanNum, maskFileName, planC, mask3M, threshold_bone)

if ~exist('planC','var')
    global planC
end

indexS = planC{end};

success = 1;

try
    if exist(maskFileName,'file')
        delete(maskFileName);
    end

    if ~isempty(threshold_bone)

        % Write .mha for scanNum
        [uniformCT, uniformScanInfoS] = getUniformizedCTScan(0,scanNum,planC);
        uniformCT = permute(uniformCT, [2 1 3]);
        uniformCT = flipdim(uniformCT,3);

        % Change data type to int16 to allow (-)ve values
        uniformCT = int16(uniformCT) - int16(planC{indexS.scan}(scanNum).scanInfo(1).CTOffset);

        uniformCTMask3M = uniformCT >= threshold_bone;

    else

        [~, uniformScanInfoS] = getUniformizedCTScan(0,scanNum,planC);

    end

    if ~isempty(mask3M)
        mask3M = permute(mask3M, [2 1 3]);
        mask3M = flipdim(mask3M,3);
    end

    if ~isempty(mask3M) && ~isempty(threshold_bone)
        mask3M = mask3M | uniformCTMask3M;
    elseif isempty(mask3M) && ~isempty(threshold_bone)
        mask3M = uniformCTMask3M;
    end

    % [dx, dy, dz]
    resolution = [uniformScanInfoS.grid2Units, uniformScanInfoS.grid1Units, uniformScanInfoS.sliceThickness] * 10;

    [xVals, yVals, zVals] = getUniformScanXYZVals(planC{indexS.scan}(scanNum));

    offset = [xVals(1) -yVals(1) -zVals(end)] * 10;

    % Write .mha file for scanNum1
    writemetaimagefile(maskFileName, mask3M, resolution, offset)

catch

    success = 0;

end


function test_bug1870

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_megplanar ft_datatype_sens ft_compute_leadfield

% this test is basically a small section of test_ft_megplanar
% the input data is consistent, but along the way the grad structure gets screwed up

load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug1870.mat'));
dataP = ft_megplanar(cfg, data);

% although it was not reported, also check on the combining of the planar channels
cfg = [];
dataC = ft_combineplanar(cfg, dataP);

% do some sanity checks
assert(isfield(dataP.grad, 'tra'));
ft_datatype_sens(dataP.grad);
ft_datatype_sens(dataC.grad);


function DCM = spm_dcm_erp_dipfit(DCM, save_vol_sens)
% Prepare structures for ECD forward model (EEG, MEG and LFP)
% FORMAT DCM = spm_dcm_erp_dipfit(DCM, save_vol_sens)
% DCM           - DCM structure
% save_vol_sens - optional argument indicating whether to perform
%                 the time consuming step required for actually using
%                 the forward model to compute lead fields (1, default)
%                 or skip it if the function is only called for
%                 verification of the input (0).
%
% Input DCM structure requires:
%       DCM.xY.Dfile
%       DCM.xY.Ic
%       DCM.Lpos
%       DCM.options.spatial - 'ERP', 'LFP' or 'IMG'
%
% fills in:
%
%       DCM.M.dipfit
%
%    dipfit.location - 0 or 1 for source location priors
%    dipfit.symmetry - 0 or 1 for symmetry constraints on sources
%    dipfit.modality - 'EEG', 'MEG', 'MEGPLANAR' or 'LFP'
%    dipfit.type     - 'ECD', 'LFP' or 'IMG''
%    dipfit.symm     - distance (mm) for symmetry constraints (ECD)
%    dipfit.Lpos     - x,y,z source positions (mm)            (ECD)
%    dipfit.Nm       - number of modes                        (Imaging)
%    dipfit.Ns       - number of sources
%    dipfit.Nc       - number of channels
%
%    dipfit.vol      - volume structure (for M/EEG)
%    dipfit.datareg  - registration structure (for M/EEG)
%__________________________________________________________________________
% Copyright (C) 2007-2015 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_dcm_erp_dipfit.m 7702 2019-11-22 11:32:26Z guillaume $

% Get data filename and good channels
%--------------------------------------------------------------------------
try
    DCM.xY.Dfile;
    DCM.M.dipfit.Ic = DCM.xY.Ic;
catch
    spm('alert*','Please specify data');
    error('Data not specified.')
end

if nargin == 1
  save_vol_sens = 0;
end

% D - SPM data structure
%--------------------------------------------------------------------------
try
    D  = spm_eeg_load(DCM.xY.Dfile);
catch
    D  = spm_eeg_load(spm_file(DCM.xY.Dfile,'filename'));
end

% set options in dipfit
%--------------------------------------------------------------------------
try, spatial  = DCM.options.spatial;  catch, spatial  = 'IMG'; end
try, location = DCM.options.location; catch, location = 0;     end
try, symmetry = DCM.options.symmetry; catch, symmetry = 0;     end

DCM.M.dipfit.type     = spatial;
DCM.M.dipfit.location = location;
DCM.M.dipfit.symmetry = symmetry;

% Get source locations if MEG or EEG
%--------------------------------------------------------------------------
switch DCM.xY.modality

    % get source priors for EEG or MEG
    %----------------------------------------------------------------------
    case{'EEG','MEG','MEGPLANAR'}

        [D, ok] = check(D, '3d');
        if ~ok
            spm('alert*',{'File not ready for source reconstruction.',...
                'Use Prepare to specify sensors and fiducials.'});
        end

        try
            DCM.M.dipfit.Lpos = DCM.Lpos;
        catch
            spm('alert*',{'Please specify source locations','in DCM.Lpos'})
        end

        DCM.M.dipfit.modality = DCM.xY.modality;
        DCM.M.dipfit.Ns       = length(DCM.Sname);
        DCM.M.dipfit.Nc       = length(DCM.xY.Ic);

        % otherwise assume LFP
        %------------------------------------------------------------------
    otherwise

        DCM.M.dipfit.modality = 'LFP';
        DCM.M.dipfit.Ns       = length(DCM.Sname);
        DCM.M.dipfit.Nc       = length(DCM.xY.Ic);
        return
end

% Detect silent sources for non-LFP type from GUI source name text
%--------------------------------------------------------------------------
DCM.M.dipfit.silent_source  = strfind(DCM.Sname,'silent');

% If not LFP, get electromagnetic forward model
%==========================================================================
if ~isfield(D, 'val'), D.val = 1; end

% detects old version of the struct
%--------------------------------------------------------------------------
if ~isfield(D, 'inv') || ~iscell(D.inv) ||...
        ~(isfield(D.inv{D.val}, 'forward') && isfield(D.inv{D.val}, 'datareg')) ||...
        ~isa(D.inv{D.val}.mesh.tess_ctx, 'char')
    D = spm_eeg_inv_mesh_ui(D, D.val);
    D = spm_eeg_inv_datareg_ui(D, D.val);
    D = spm_eeg_inv_forward_ui(D, D.val);
    save(D);
end

% fill in dipfit
%--------------------------------------------------------------------------
for m = 1:numel(D.inv{D.val}.forward)
    if strncmp(DCM.xY.modality, D.inv{D.val}.forward(m).modality, 3)
        DCM.M.dipfit.vol      = D.inv{D.val}.forward(m).vol;
        DCM.M.dipfit.datareg  = D.inv{D.val}.datareg(m);
        if isfield(D.inv{D.val}.forward(m), 'siunits') && D.inv{D.val}.forward(m).siunits
            DCM.M.dipfit.sens     = D.inv{D.val}.forward(m).sensors;
            DCM.M.dipfit.siunits  = true;
        else
            DCM.M.dipfit.sens     = DCM.M.dipfit.datareg.sensors;
            DCM.M.dipfit.siunits  = false;
        end
    end
end

% channels
%--------------------------------------------------------------------------
if save_vol_sens
    if ischar(DCM.M.dipfit.vol)
        DCM.M.dipfit.vol = ft_read_headmodel(DCM.M.dipfit.vol);
    end

    [DCM.M.dipfit.vol, DCM.M.dipfit.sens] = ft_prepare_vol_sens(DCM.M.dipfit.vol, ...
        DCM.M.dipfit.sens, 'channel', D.chanlabels(DCM.xY.Ic));
end

switch DCM.options.spatial

    % Imaging (distributed source reconstruction)
    %----------------------------------------------------------------------
    case{'IMG'}

        % Load Gain or Lead field matrix
        %------------------------------------------------------------------
        DCM.val = D.val;
        [L,D]   = spm_eeg_lgainmat(D, [], D.chanlabels(DCM.xY.Ic));

        % centers
        %------------------------------------------------------------------
        xyz = DCM.M.dipfit.Lpos;
        Np  = size(xyz,2);

        % parameters
        %==================================================================

        % defaults: Nm = 6; number of modes per region
        %------------------------------------------------------------------
        try, rad  = DCM.M.dipfit.radius; catch, rad  = 16;    end
        try, Nm   = DCM.M.dipfit.Nm;     catch, Nm   = 6;     end

        % Compute spatial basis (eigenmodes of lead field)
        %==================================================================

        % create MSP spatial basis set in source space
        %------------------------------------------------------------------
        vert   = D.inv{D.val}.mesh.tess_mni.vert;
        for i  = 1:Np
            Dp = sum([vert(:,1) - xyz(1,i), ...
                      vert(:,2) - xyz(2,i), ...
                      vert(:,3) - xyz(3,i)].^2,2);

            % nearest mesh points
            %--------------------------------------------------------------
            Ip = find(Dp < rad^2);
            if length(Ip) < Nm;
                [y,Ip] = sort(Dp);
                Ip     = Ip(1:Nm);
            end

            % left hemisphere
            %--------------------------------------------------------------
            U                  = spm_svd(L(:,Ip)',0);
            U                  = U(:,1:Nm);
            DCM.M.dipfit.G{i}  = L(:,Ip)*U;
            DCM.M.dipfit.U{i}  = U;
            DCM.M.dipfit.Ip{i} = Ip;
        end

        % Save results
        %==================================================================
        DCM.M.dipfit.radius  = rad;                   % VOI (XYZ, Radius)
        DCM.M.dipfit.Nm      = Nm;                    % modes per region
        DCM.M.dipfit.Nd      = length(vert);          % number of dipoles
        DCM.M.dipfit.gainmat = D.inv{D.val}.gainmat;  % Lead field filename

    otherwise

end


function test_ft_plot_crosshair

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_plot_crosshair

close all

result = {};
figure; ft_plot_axes([], 'unit', 'mm'); ft_plot_crosshair([100 100 100], 'color', 'm'); view([1 0.5 0.5]); result{end+1} = getframe;
figure; ft_plot_axes([], 'unit', 'mm'); ft_plot_crosshair([100 100 100], 'color', 'y'); view([1 0.5 0.5]); result{end+1} = getframe;
figure; ft_plot_axes([], 'unit', 'mm'); ft_plot_crosshair([100 100 100], 'color', [0 0 0]); view([1 0.5 0.5]); result{end+1} = getframe;
figure; ft_plot_axes([], 'unit', 'mm'); ft_plot_crosshair([100 100 100], 'color', 'powderblue'); view([1 0.5 0.5]); result{end+1} = getframe;
figure; ft_plot_axes([], 'unit', 'mm'); ft_plot_crosshair([100 100 100], 'color', 'limegreen'); view([1 0.5 0.5]); result{end+1} = getframe;

% all iterations were done with (slightly) different options, hence the results should not be equal
for i=1:numel(result)
  for j=(i+1):numel(result)
    assert(~isequal(result{i}, result{j}));
  end
end


function size = varsize(X, units)
%VARSIZE Returns the size of a variable in bytes.
% Usage:
%   size = varsize(X)
%   size = varsize(X, units) % 'bytes' (default), 'KB', 'MB', 'GB'
%
% See also: whos
narginchk(1, 2)
if nargin < 2
    units = 'bytes';
end

% Get variable size in bytes
S = whos('X');
size = S.bytes;

if nargout < 1
    % Just output to console if not storing variable
    disp(bytes2str(size, 4))
    clear size
    return
end

% Convert to units
switch lower(units)
    case {'kb', 'k', 'kilo', 'kilobyte', 'kib'}
        size = size / 1024;
    case {'mb', 'm', 'mega', 'megabyte', 'mib'}
        size = size / 1024 / 1024;
    case {'gb', 'g', 'giga', 'gigabyte', 'gib'}
        size = size / 1024 / 1024 / 1024;
    case {'auto', 'str'}
        size = bytes2str(size, 4);
    otherwise
        return
end

end


% This subroutine "overlay.m" is called from varios
% program (view_*.m, subcata.m). It plots an overlay
% of coastlines, faults, earthquakes etc on a map.
% This file should be customized for each region

%  Stefan Wiemer   11/94

report_this_filefun(mfilename('fullpath'));

global main mainfault faults coastline vo

figure_w_normalized_uicontrolunits(map)
ax = axis;
if ax(1) < min(coastline(:,1)) | ax(2) > min(coastline(:,1))
    disp([' Regetting coastline ... ']);
    struc = gshhs2('gshhs_h.b',[s4_south s3_north],[s2_west s1_east] );
    s2_west = ax(1);s1_east = ax(2);s3_north = ax(4);s4_south = ax(3);
end
%delete(mapplot);delete(plovo);delete(epimax);

[i,j ] = size(struc);
lat = [];
lon = [];
lat2 = [];
lon2 = [];
figure_w_normalized_uicontrolunits(map)
hold on
for i = 1:j
    if struc(i).tag(1:4) == 'land' | struc(i).tag(1:4) == 'isla'
        lat = [lat ; struc(i).lat ];
        lon = [lon ; struc(i).long];
        l1 = [  struc(i).lat ];
        l2 =   [  struc(i).long];
        l = isnan(l1); l1(l) = [];
        l = isnan(l2); l2(l) = [];
        fill(l2,l1,[0.9 0.9 0.9]);
        hold on
    end

    if struc(i).tag(1:4) == 'lake'
        lat2 = [struc(i).lat ];
        lon2 = [struc(i).long];
        l1 = [  struc(i).lat ];
        l2 =   [  struc(i).long];
        l = isnan(l1); l1(l) = [];
        l = isnan(l2); l2(l) = [];
        fill(l2,l1,[0.85 0.85 1]);
        hold on
    end
end

coastline = [lon lat];

hold on
if exist('coastline', 'var')
    if isempty(coastline) ==  0
        mapplot = plot(coastline(:,1),coastline(:,2));
        set(mapplot,'LineWidth',1.0,'Color',[0  0      0 ])
    end
end
if exist('vo', 'var')
    if isempty(vo) ==  0
        plovo = plot(vo.Longitude,vo.Latitude,'^r');
        set(plovo,'LineWidth',1.5,'MarkerSize',6,...
            'MarkerFaceColor','w','MarkerEdgeColor','r');
    end
end

% plot the well location
if exist('well', 'var')
    if isempty(well) ==  0
        i = find(well(:,1) == inf);
        plowe = plot(well(i+1,1),well(i+1,2),'d');
        set(plowe,'LineWidth',1.5,'MarkerSize',6,...
            'MarkerFaceColor','k','MarkerEdgeColor','k');
    end
end

%plot main faultline

if exist('mainfault', 'var')
    if isempty(mainfault) == 0
        plo3 = plot(mainfault(:,1),mainfault(:,2),'b');
        set(plo3,'LineWidth',3.0)
    end  % if exist mainfault
end

%
% plot big earthquake epicenters with a 'x' and the data/magnitude
%
if exist('maepi', 'var')
    if isempty(maepi) == 0
        epimax = plot(maepi(:,1),maepi(:,2),'hm');
        set(epimax,'LineWidth',1.5,'MarkerSize',12,...
            'MarkerFaceColor','y','MarkerEdgeColor','k')

        stri2 = [];
        for i = 1:length(maepi(:,1));
            s = sprintf('   %3.1f M=%3.1f',maepi(i,3),maepi(i,6));
            stri2 = [stri2 ; s];
        end   % for i
        te1 = text(maepi(:,1),maepi(:,2),stri2);
        set(te1,'FontWeight','normal','Color','k','FontSize',9,'Clipping','on')
    end  %  if length(maepi)
end  %  if length(maepi)

%plot mainshock(s)
%
if exist('main', 'var')
    if isempty(main) == 0
        plo1 = plot(main(:,1),main(:,2),'*k');
        set(plo1,'MarkerSize',12,'LineWidth',2.0)
    end  % if main
end

if exist('faults', 'var')
    if isempty(faults) == 0
        plo4 = plot(faults(:,1),faults(:,2),'k');
        set(plo4,'LineWidth',0.2)
    end  % if exist faults
end
%axis([ s2_west s1_east s4_south s3_north])


function tc_plotSubplots(tc, plotMeanFlag, parent);
% tc_plotSubplots(tc, <plotMeanFlag=1>, <parent=tc.ui.plot panel>);
%
% Plots each condition in a separate subplot of
% the tc UI figure. If plotMeanFlag is set to
% 1 (default), plots mean TC with error bars;
% otherwise, plots all trials.
%
% 10/04 ras.
% 03/05 changed colors so they reflect trial #
% kgs 031605 changed colors to reflect trial number
% ras 03/16/05 amended this: will color diff't trials if 'legend'
% is selected
if nargin<1,    tc = get(gcf,'UserData');     end
if nargin<2,    plotMeanFlag = 1;             end
if nargin<3,    parent = tc.ui.plot;          end
if parent==gcf | parent==get(gcf, 'CurrentAxes')
    % make a uipanel to fit on the target
    parent = uipanel('Parent', parent, ...
                     'Units', 'normalized', ...
                     'BackgroundColor', get(gcf, 'Color'), ...
                     'Position', [0 0 1 1])
end

% params
sameAxes = 1; % if 1, will set all subplots to
              % have the same axis bounds
columnMajor = 1;   % plot conditions along columns

% init axes
axes('Parent', parent);
cla
% otherAxes = findobj('Parent', parent, 'Type', 'axes');
% delete(otherAxes);

conds = find(tc_selectedConds(tc));
nConds = length(conds);
nrows = ceil(sqrt(nConds));
ncols = ceil(nConds/nrows);

maxTrials = max(squeeze(sum(~isnan(tc.allTcs(1,:,conds)))));
% altColors = (tc.params.legend==1 & plotMeanFlag==0 & maxTrials < 10);
try
    altColors = tc.params.markEachTrial;
catch
    altColors = 0 % back compatibility
end

%% get peri-stimulus time sample points
t = tcGet(tc, 't');

%% main loop: plot each condition
for c = 1:nConds
    if columnMajor==1
        col = ceil(c/nrows);
        row = mod(c-1,nrows) + 1;
        pos = (row-1)*ncols + col;
    else
        pos = c;
    end

    subplotHandles(c) = subplot(nrows,ncols,pos);

    i = conds(c);
    cond = tc.trials.condNums(i);
    col = tc.trials.condColors{i};
    name = tc.trials.condNames{i};

    if plotMeanFlag==1
        htmp = errorbar(t, tc.meanTcs(:,i), tc.sems(:,i));
        set(htmp, 'Color', col, 'LineWidth', 2.5);
    else
        htmp = plot(t, tc.allTcs(:,:,i));
        if altColors==0
            set(htmp, 'Color', col, 'LineWidth', 1);
        else
            setLineColors( jet(maxTrials) );
        end
    end

    % indicate conditions with titles
    title(name);

    if tc.params.grid==1
        grid on
    end

    if isfield(tc.params, 'axisBounds') & ~isempty(tc.params.axisBounds)
        axis(tc.params.axisBounds);
    else
        axis tight
    end

    % if normalizing axis bounds, record them for this subplot
    if sameAxes==1
        allAX(c,:) = axis;
    end
end

% normalize axis bounds if selected
if sameAxes==1
    maxAX = [allAX(1,1) allAX(1,2) min(allAX(:,3)) max(allAX(:,4))];
    for c = subplotHandles
        subplot(c);
        axis(maxAX);
        axis off
    end
    if columnMajor==1
        corner = nrows;
    else
        corner = (nrows-1)*ncols + 1;
    end
    subplot(subplotHandles(corner)); axis on; set(gca, 'Box', 'off');
end

% label only appropriate subplots
for c = 1:nConds
    subplot(subplotHandles(c));
    if columnMajor==1
        if ceil(c/nrows)==1
			ylabel('% Signal');
        end
        if mod(c-1, nrows)+1==nrows
        	xlabel('Trial time, secs');
        end
    else
        if mod(c, ncols)==1
			ylabel('% Signal');
        end
        if ceil(c/nrows)==nrows
        	xlabel('Trial time, secs');
        end
    end
end

% indicate the peak and baseline periods, if selected
if tc.params.showPkBsl==1
    for c = 1:nConds
        subplot(subplotHandles(c));
        hold on
        AX = axis;
        plot(tc.bslPeriod, repmat(AX(3), size(tc.bslPeriod)), ...
            'k', 'LineWidth', 3);
        plot(tc.peakPeriod, repmat(AX(4), size(tc.peakPeriod)), ...
            'r', 'LineWidth', 4);
    end
end

if altColors==1
% 	% add legend that indicates trial number to last subject plot
	for j=1:tc_numTrials(tc)
        legendtext{j} = num2str(j);
    end

	hleg = legend(legendtext, -1);
    legend(hleg, 'Boxoff', 'Location', 'BestOutside')

%     axes(hleg)
%     xlabel('Trial #')
%     legendPanel(legendtext);
end

% add the handles to the user data
tc.ui.subplotHandles = subplotHandles;
set(gcf, 'UserData', tc);

return


function lstAct = mlAct_Matrix2IndexList(mlAct, ml)
lstAct = [];
for iCh = 1:size(ml,1)
    if size(ml,2)==4
        k = find(mlAct(:,1)==ml(iCh,1)  &  mlAct(:,2)==ml(iCh,2)  &  mlAct(:,4)==ml(iCh,4));
    else
        k = find(mlAct(:,1)==ml(iCh,1)  &  mlAct(:,2)==ml(iCh,2));
    end
    if mlAct(k,3)==1
        lstAct = [lstAct; iCh];
    end
end


function skeleton_plot(cc, lab, varargin)
% SKELETON_PLOT  Plot a labelled segmentation and its skeleton
%
% SKELETON_PLOT(CC, LAB)
%
%   CC and LAB are the outputs from function skeleton_label().
%
%   This function plots the branches from the skeleton with the two end
%   points of each one (note than several branches can share the same end
%   point). If LAB is provided and not empty, the branches are plotted on
%   the labelled segmentation.
%
% SKELETON_PLOT(CC, LAB, ...)
%
%   It is possible to add more input arguments, that will be passed to the
%   plot functions. See 'help plot' for the available options.
%
% See also: skeleton_label.

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2011 University of Oxford
% Version: 0.2.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% 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. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% check arguments
error(nargchk(1, Inf, nargin, 'struct'));
error(nargoutchk(0, 1, nargout, 'struct'));

% defaults
col = 'b';

% save hold status for later
HOLD = ishold;

% plot
if (nargin > 1 && ~isempty(lab))
    imagesc(lab)
    axis xy
    hold on
    col = 'w';
end

% loop every branch in the skeleton
for I = 1:cc.NumObjects
    % list of voxels in current branch
    br = cc.PixelIdxList{I};

    % plot skeleton branches
    if (length(cc.ImageSize) == 2)
        % convert image linear indices to image r, c, s indices
        [r, c] = ind2sub(cc.ImageSize, br);

        % plot branch in order
        plot(c, r, col, varargin{:})
        hold on

        % plot starting and end points
        plot(c([1 end]), r([1 end]), [col 'o'], varargin{:})
    elseif (length(cc.ImageSize) == 3)
        % convert image linear indices to image r, c, s indices
        [r, c, s] = ind2sub(cc.ImageSize, br);

        % plot branch in order
        plot3(c, r, s, 'w', varargin{:})
        hold on

        % plot starting and end points
        plot3(c([1 end]), r([1 end]), s([1 end]), [col 'o'], varargin{:})
    else
        error('Can only print 2D or 3D skeletons')
    end
end

% recover hold status
if HOLD
    hold on
else
    hold off
end


function [d1, d2, sel] = partition(d, sel, p)

% PARTITION - partition a DATA_GLOBAL object randomly or deterministically
%
% D1 = PARTITION(D, SEL)
% [D1, D2] = PARTITION(D, SEL)
% [D1, D2, SEL] = PARTITION(D, 'rand', P)
%
% The same as the DATA/PARTITION method, except that it operates on
% DATA_GLOBAL objects, manipulating D.index, and D.myX and D.myY if
% present.

n = length(d.index);

sel = sel(:);
if ischar(sel)
    if ~strcmp(lower(sel'), 'rand'), error(['unknown option ''' sel' '''']), end
    if nargin < 3, p = 0.5; end
    if ~isnumeric(p) | prod(size(p)) ~= 1, error('P must be a numeric scalar'), end
    p = full(real(double(p)));
    if p < 0
        error('P may not be negative')
    elseif p > n
        error('P may not be larger than the number of data points')
    elseif p < 1
        sel = (rand(n, 1) < p);
    elseif p ~= round(p)
        error('P must either be a probability, or a positive integer')
    else
        sel = randperm(n)';
        sel = sel(1:p);
    end
end
if islogical(sel)
    if length(sel) ~= n
        error('logical array must have one element per data point')
    end
elseif ~isreal(sel) | ~isnumeric(sel)
    error('SEL should be a logical array or an array of valid indices')
else
    sel = full(double(sel));
    if any(sel < 1 | sel > n | sel ~= round(sel))
        error('invalid/out of range indices')
    end
    z = logical(zeros(n,1));
    z(sel) = 1;
    sel = z;
end

d1 = d;
d1.index(~sel) = [];
if ~isempty(d1.myX), d1.myX(~sel, :) = []; end
if ~isempty(d1.myY), d1.myY(~sel, :) = []; end

if nargout < 2, return, end

d2 = d;
d2.index(sel) = [];
if ~isempty(d2.myX), d2.myX(sel, :) = []; end
if ~isempty(d2.myY), d2.myY(sel, :) = []; end


function [vert, face] = read_ply(fn)

% READ_PLY reads triangles, tetraheders or hexaheders from a Stanford *.ply file
%
% Use as
%   [vert, face, prop, face_prop] = read_ply(filename)
%
% Documentation is provided on
%   http://paulbourke.net/dataformats/ply/
%   http://en.wikipedia.org/wiki/PLY_(file_format)
%
% See also WRITE_PLY, WRITE_VTK, READ_VTK

% Copyright (C) 2013-2018, Robert Oostenveld
%
% $Id$

fid = fopen_or_error(fn, 'r');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the file starts with an ascii header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

line = readline(fid);
if ~strcmp(line, 'ply')
  fclose(fid);
  ft_error('unexpected header line');
end
line = readline(fid);

if ~strncmp(line, 'format', 6)
  fclose(fid);
  ft_error('unexpected header line');
else
  format = line(8:end);
end
line = readline(fid);

if ~strncmp(line, 'element vertex', 14)
  fclose(fid);
  ft_error('unexpected header line');
else
  nvert = str2double(line(16:end));
end
line = readline(fid);

prop = [];
while strncmp(line, 'property', 8)
  tok = tokenize(line);
  prop(end+1).format = tok{2};
  prop(end  ).name   = tok{3};
  line = readline(fid);
end

if ~strncmp(line, 'element face', 12)
  fclose(fid);
  ft_error('unexpected header line');
else
  nface = str2double(line(14:end));
end
line = readline(fid);

if ~strcmp(line, 'property list uchar int vertex_index')    && ...
    ~strcmp(line, 'property list uchar int vertex_indices') && ...
    ~strcmp(line, 'property list uchar uint vertex_index')  && ...
    ~strcmp(line, 'property list uchar uint vertex_indices')
  % the wikipedia documentation specifies vertex_index, but the OPTOCAT files have vertex_indices

  % it would not be very difficult to enhance the reader here with another
  % representation of the faces, i.e. something else than "uchar int"
  fclose(fid);
  ft_error('unexpected header line');
end
line = readline(fid);

while ~strcmp(line, 'end_header')
  line = readline(fid);
end

offset = ftell(fid);
fclose(fid);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the file continues with a section of data, which can be ascii or binary
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

switch format

  case 'ascii 1.0'

    fid = fopen_or_error(fn, 'rt');
    fseek(fid, offset, 'cof');
    dat = fscanf(fid,'%f',[numel(prop), nvert])';
    for j=1:length(prop)
      vert.(prop(j).name) = dat(:,j);
    end
    face = zeros(nface,0);
    num = zeros(nface,1);
    for i=1:nface
      % each polygon can have a different number of elements
      num(i) = fscanf(fid,'%f',1);
      face(i,1:num(i)) = fscanf(fid,'%f',num(i));
    end
    fclose(fid);

  case 'binary_little_endian 1.0'

    fid = fopen_or_error(fn, 'rb', 'l');
    fseek(fid, offset, 'cof');

    dat = zeros(nvert,length(prop));
    for i=1:nvert
      for j=1:length(prop)
        dat(i,j) = fread(fid, 1, prop(j).format);
      end % for each property
    end % for each vertex
    for j=1:length(prop)
      switch prop(j).format
        % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64
        case 'char'
          vert.(prop(j).name) = uint8(dat(:,j));
        case 'uchar'
          vert.(prop(j).name) = uint8(dat(:,j));
        case 'short'
          vert.(prop(j).name) = int16(dat(:,j));
        case 'ushort'
          vert.(prop(j).name) = uint16(dat(:,j));
        otherwise
          vert.(prop(j).name) = dat(:,j);
      end
    end
    clear dat;

    face = zeros(nface,0);
    num  = zeros(nface,1);
    for i=1:nface
      % each polygon can have a different number of elements
      num(i) = fread(fid, 1, 'uint8');
      face(i,1:num(i)) = fread(fid, num(i), 'int32');
    end
    fclose(fid);

  case 'binary_big_endian 1.0'
    % this is exactly the same as the code above, except that the file is opened as big endian

    fid = fopen_or_error(fn, 'rb', 'b');
    fseek(fid, offset, 'cof');

    dat = zeros(nvert,length(prop));
    for i=1:nvert
      for j=1:length(prop)
        dat(i,j) = fread(fid, 1, prop(j).format);
      end % for each property
    end % for each vertex
    for j=1:length(prop)
      switch prop(j).format
        % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64
        case 'char'
          vert.(prop(j).name) = uint8(dat(:,j));
        case 'uchar'
          vert.(prop(j).name) = uint8(dat(:,j));
        case 'short'
          vert.(prop(j).name) = int16(dat(:,j));
        case 'ushort'
          vert.(prop(j).name) = uint16(dat(:,j));
        otherwise
          vert.(prop(j).name) = dat(:,j);
      end
    end
    clear dat;

    face = zeros(nface,0);
    num  = zeros(nface,1);
    for i=1:nface
      % each polygon can have a different number of elements
      num(i) = fread(fid, 1, 'uint8');
      face(i,1:num(i)) = fread(fid, num(i), 'int32');
    end
    fclose(fid);

  otherwise
    ft_error('unsupported format');
end % switch

% each polygon can have a different number of elements
% mark all invalid entries with nan
if any(num<size(face,2))
  for i=1:nface
    face(i,(num(i)+1):end) = nan;
  end
end % if

if numel(face)>0
  % MATLAB indexes start at 1, inside the file they start at 0
  face = face+1;
end

end % function read_ply

function line = readline(fid)
% read the next line from the ascii header, skip all comment lines
line = fgetl(fid);
while strncmp(line, 'comment', 7)
  line = fgetl(fid);
end
end % function readline


%% PSWARM Install for OPTI Toolbox
% Copyright (C) 2012 Jonathan Currie (I2C2)

% This file will help you compile PSwarm for use with MATLAB.

% My build platform:
% - Windows 8 x64
% - Visual Studio 2012
% - Intel Math Kernel Library

% To recompile you will need to get / do the following:

% 1) Get PSwarm
% PSwarm is available from http://www.norg.uminho.pt/aivaz/pswarm/.
% Download PPSwarm_vxx.zip (C Version) and unzip to a suitable location.

% 2) Compile PSwarm
% The easiest way to compile PSwarm is to use the Visual Studio Project
% Builder included with OPTI. Use the following commands, substituting the
% required path on your computer:
%
% %% Visual Studio Builder Commands
% path = 'full path to PSwarm here'; %e.g. 'C:\Solvers\PSwarm'
% sdir = path;
% name = 'libpswarm';
% opts.exPP = {'LINEAR','_CRT_SECURE_NO_WARNINGS','_CRT_NONSTDC_NO_DEPRECATE'};
% opts.exclude = {'showcache.c','user.c','pswarm_main.c','pswarm_py.c','pswarm_r.c','cache.c'};
% VS_WriteProj(sdir,name,[],opts)
% %%
%
% Once complete, you will have a directory called PSwarm\libpswarm. Open the
% Visual Studio 2012 project file, then complete the following steps:
%   a) A couple code changes are required in order to interface with OPTI:
%       - In pswarm.h add "int solveriters;" to the Stats structure as the
%       last line.
%       - In pswarm.h change the define on line 62 to
%         "#define SYS_RANDOM 1"
%       - In pswarm.c on line 666 add "stats.solveriters = iter;"
%       - Change the structure definitions in pswarm.c at line 66 to extern:
%           "extern struct Stats stats;"
%           "extern struct Options opt;"
%       - Comment the default options structure in pswarm.c on line 70
%       (comment all lines for this structure).
%   b) Build a Win32 or x64 Release to compile the code.
%   c) Copy the generated .lib file to the following folder:
%
%   OPTI/Solvers/pswarm/Source/lib/win32 or win64
%
%   You will also need to copy pswarm.h to the following folder:
%
%   OPTI/Solvers/pswarm/Source/Include

% 3) PSwarm MEX Interface
% The PSwarm MEX Interface is a simple MEX interface I wrote to use PSwarm.

% 4) Compile the MEX File
% The code below will automatically include all required libraries and
% directories to build the PSwarm MEX file. Once you have completed all the
% above steps, simply run this file to compile PSwarm! You MUST BE in the
% base directory of OPTI!

clear pswarm

% Modify below function if it cannot find Intel MKL on your system.
mkl_link = opti_FindMKL();
% Get Arch Dependent Library Path
libdir = opti_GetLibPath();

fprintf('\n------------------------------------------------\n');
fprintf('PSwarm MEX FILE INSTALL\n\n');

%Get PSwarm Libraries
post = [' -IInclude -L' libdir ' -llibpswarm -llibut -output pswarm'];
%Get MKL Libraries (for BLAS)
post = [post mkl_link];

%CD to Source Directory
cdir = cd;
cd 'Solvers/pswarm/Source';

%Compile & Move
pre = 'mex -v -largeArrayDims pswarmmex.c';
try
    eval([pre post])
    movefile(['pswarm.' mexext],'../','f')
    fprintf('Done!\n');
catch ME
    cd(cdir);
    error('opti:pswarm','Error Compiling PSwarm!\n%s',ME.message);
end
cd(cdir);
fprintf('------------------------------------------------\n');


function snakedemo2
% SNAKEDEMO - Example on how to build a Snake Toy, and twist
%             it into predefined shapes.
%

% Copyright (C) 2005-2011 The MathWorks Inc.

%%
  function b = oneblock(dark, parent)
  % Create one snake block.
  % DARK is boolean, true if this is a dark block.
  % PARENT is the object that is the parent of the new block.

    % The transform object is going to be our BLOCK representation.
    % The patches in the transform are the visible aspect of that block.
    b = hgtransform('parent',parent);

    % Create the patches.  Coordinate map.
    %
    %     SIDE         TOP/BACK
    %
    %  -1     1      -1     1
    % -1X-----X      X------X -1
    %   |    /       |      |
    %   |   /        |      |
    %   |  /         |      |
    %   | /          |      |
    %   |/           |      |
    % 1 X            X------X 1
    %
    %                  B (1 -1 -1)
    %               __+
    %(-1 -1 -1) __--   --__
    %  A    __--           --__
    %     +-                 __+  F  (1 -1 1)
    %     |--__          __-- /
    %     |    --__  __--    /
    %     |        +-       /
    %     |        |  E    /
    %     |        |      /  (-1 -1 1)
    %     |        |     /
    %     |        |    /
    %     |        |   /
    %     +        |  /
    %   C  --__    | /
    %          --__|/
    %(-1 1 -1)     +
    %                D  (-1 1 1)

    v = [ -1 -1 -1 ;
          1 -1 -1 ;
          -1 1 -1 ;
          -1 1 1 ;
          -1 -1 1 ;
          1 -1 1 ;
        ];

    A = 1;
    B = 2;
    C = 3;
    D = 4;
    E = 5;
    F = 6;

    f = [ A B C nan
          E F D nan
          A B F E
          A E D C
          C D F B
        ];

    %
    % Specify the face color for each block in the snake
    % as either a cream color, or brown.
    %
    if dark
      fc = [ .4 .4 .2 ];
    else
      fc = [ 1 1 .9 ];
    end

    patch('parent',b, ...
          'vertices', v, ...
          'faces', f, ...
          'facecolor',fc, ...
          'edgecolor','k');

    % Transformation function that moves each block
    % into the correct location within the parent.
    xform(b,0);

    % Remember the current rotation value for animation.
    setappdata(b,'rotation',0);
  end

%%
  function xform(block, rotation)
  % Apply a transform to BLOCK.
  % ROTATION is the amount of rotation off the default for that blcck.

    % Create the compound transform.
    tform = makehgtform('axisrotate',[0 1 0],rotation,...
                        'zrotate',pi/2,'yrotate',pi,...
                        'translate',[2 0 0]);

    % Apply the transformation to BLOCK.
    % Remember that BLOCK is an hgtransform object, and not
    % A patch object.  The patch just goes along for the ride.
    set(block,'matrix',tform);
  end

  %%
  % Create the Figure window and Axesin which we are going to create the
  % snake.

  figure('renderer','opengl');
  title('Snake Demo');
  % Force the axes to have sane aspect ratios.
  axis vis3d
  % Make the axes visible.  Allow objects to be drawn outside
  % the axes clip rectangle.
  set(gca,'vis','off','clip','off');
  set(gca,'pos',[0 0 1 1]);
  % Start with an off-angle view.
  view(3)

  % Create the first block.
  snake(1) = oneblock(false, gca);

  % We need 24 blocks to make a traditional snake toy.
  for i = 2:24
    snake(i) = oneblock(~mod(i,2),snake(i-1));
  end

  %%
  % We intend to animate snake transformations.
  % To do this so it is reliable on multiple platforms,
  % running at different speeds, we need to measure the time
  % it takes to draw, and then add a pause so the animation
  % is not too fast.
  function docam

    % Orbit the camera so there is lots of movement.
    % Good orbit values are usuall two numbers, where
    % the second value is slightly smaller than the first.
    camorbit(5,3);

    % Measure how long it takes to draw the snake.
    % We could use drawnow('expose'), but it is nice to
    % let someone use camera toolbar and menu items
    % while the snake is animating.
    tic
      drawnow;
    h=toc;

    % Calculate the delta between the desired pause of .04 seconds.
    delta = .04-h;

    % Add more delay
    if delta > 0
      pause(delta);
    end
  end

  %%
  % To animate the snake, we need a routine to permute the snake
  % to new angles.
  function config(in, conf)

    % Loop over all the blocks in order.
    for k=1:length(in)

      % Fetch the old rotation value from the input block.
      old = getappdata(in(k),'rotation');

      % Create an animation step value for 10 total steps.
      step = (conf(k)-old)/10;

      % Skip blocks already configured
      if step ~= 0

        % Perform the animation.
        for j = 1:10
          % Use the same transform function as we had before.
          xform(in(k),old+(step*j));
          docam;
        end
      end

      % Solve any round-off problems in the animation.
      xform(in(k),conf(k));
      % Store the new value into the block
      setappdata(in(k),'rotation',conf(k));
    end
    % Float the camera around a little bit so you can
    % Get the feel for what's going on.
    for k=1:50
      docam;
    end

  end

  %%
  % Perform some animations.
  %
  % By defining pre-defined rotation vectors, we can animate
  % the snake through different permutations.

  % Convenient name for 90 degrees.
  n=pi/2;

  %% Ball
  rv = [ 0 n -n -n n -n n n -n n -n -n ...
         n -n n n -n n -n -n n -n n n];
  config(snake, rv);
  %% Wave
  rv = [ 0 0 pi 0 pi 0 pi 0 pi 0 pi 0 ...
         pi 0 pi 0 pi 0 pi 0 pi 0 pi 0];
  config(snake, rv);
  %% Dna
  rv = [ n n n n n n n n n n n n ...
         n n n n n n n n n n n n];
  config(snake, rv);
  %% Spiral
  rv = [ 0 n 0 n 0 n 0 n 0 n 0 n ...
         0 n 0 n 0 n 0 n 0 n 0 n];
  config(snake, rv);
  %% Coil
  rv = [ 0 n pi n pi n pi n pi n pi n ...
         pi n pi n pi n pi n pi n pi n];
  config(snake, rv);
  %% box
  rv = [ 0 0 0 0 0 0 pi 0 0 0 0 ...
         pi 0 0 0 0 0 0 pi 0 0 0 0 pi];
  config(snake, rv);
  %% filledbox
  rv = [ 0 pi 0 0 0 pi pi 0 0 0 0 pi ...
         0 0 pi 0 0 0 0 pi pi 0 0 0];
  config(snake, rv);
  %% cross
  rv = [ 0 0 0 pi pi 0 0 0 pi 0 pi pi ...
         0 pi 0 pi pi 0 pi 0 pi pi 0 pi];
  config(snake, rv);
  %% heart
  rv = [ 0 0 pi 0 0 n 0 n 0 0 0 0 ...
         pi 0 0 0 0 -n 0 -n 0 0 pi 0];
  config(snake, rv);
  %% dog
  rv = [ 0 pi 0 0 0 pi pi 0 pi 0 0 ...
         pi 0 pi pi 0 0 0 pi 0 pi pi 0 pi ];
  config(snake, rv);
  %% chicken
  rv = [ 0 pi 0 0 0 0 0 pi pi 0 ...
         n 0 pi pi 0 pi pi 0 -n ...
         0 pi pi 0 0];
  config(snake, rv);
  %% swan
  rv = [ 0 pi pi 0 0 0 0 0 pi -n -n -n ...
         n -n n n -n n -n -n -n pi 0 pi];
  config(snake, rv);
  %% duck
  rv = [ 0 pi pi 0 0 0 n 0 n 0 0 -n ...
         pi n 0 0 n pi -n 0 0 n 0 n];
  config(snake, rv);
  %% robot
  rv = [ 0 0 n 0 -n n n n -n -n -n -n ...
         pi n n n n -n -n -n n 0 -n 0];
  config(snake, rv);
  %% symbol
  rv = [ 0 pi 0 pi n n -n n -n -n pi 0 ...
         pi pi 0 pi n n -n n -n -n pi 0];
  config(snake, rv);
  %% fluer
  rv = [ 0 0 n -n n 0 pi 0 -n n -n 0 ...
         pi 0 n -n n 0 pi 0 -n n -n 0];
  config(snake, rv);
  %% bowl
  rv = [ 0 0 pi pi 0 n -n pi n n -n -n ...
         pi n n -n -n pi n n -n -n pi n];
  config(snake, rv);
  %% spring
  rv = [ 0 -n n 0 n -n n 0 n -n n 0 ...
         n -n n 0 n -n n 0 n -n n 0];
  config(snake, rv);
  %% cobra
  rv = [ 0 pi -n 0 0 0 pi n n 0 pi 0 0 ...
         0 n 0 pi pi 0 pi pi 0 n 0];
  config(snake, rv);
  %% line
  rv = [ 0 0 0 0 0 0 0 0 0 0 0 0 ...
         0 0 0 0 0 0 0 0 0 0 0 0];
  config(snake, rv);

end


function output = callnone(interfacedata)

% Standard interface
output.Primal      = zeros(length(interfacedata.c),1);
output.Dual        = [];
output.Slack       = [];
output.problem     = -2;
output.infostr     = yalmiperror(-2,'YALMIP');
output.solverinput = [];
output.solveroutput= [];
output.solvertime  = 0;


function g = gold()
  % GOLD return a gold color
  %
  % g = gold()
  %
  % Outputs:
  %   g  1 by 3 gold rgb values
  %

  g = [255 228  58]/255;

end


% GPTOOLBOXES Load in the relevant toolboxes for GP.

importLatest('netlab');
importLatest('mocap');
importTool('ndlutil');
importLatest('prior');
importLatest('mltools');
importLatest('optimi');
importLatest('datasets');
importLatest('kern');
importLatest('noise'); % Only needed for C++ load ins.


function varargout = process_average_freq( varargin )
% PROCESS_AVERAGE_FREQ: For each file in input, compute the average of the different frequency bands.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2016

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Average frequency bands';
    sProcess.Category    = 'File';
    sProcess.SubGroup    = 'Average';
    sProcess.Index       = 303;
    sProcess.Description = '';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'timefreq'};
    sProcess.OutputTypes = {'timefreq'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    % === OVERWRITE
    sProcess.options.overwrite.Comment = 'Overwrite input files';
    sProcess.options.overwrite.Type    = 'checkbox';
    sProcess.options.overwrite.Value   = 0;
    sProcess.options.overwrite.Group   = 'output';
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFile = Run(sProcess, sInput) %#ok<DEFNU>
    OutputFile = [];
    isOverwrite = sProcess.options.overwrite.Value;
    % Load TF file
    TimefreqMat = in_bst_timefreq(sInput.FileName, 0);
    % Check for measure
    if strcmpi(TimefreqMat.Measure, 'none')
        bst_report('Error', sProcess, sInput, 'Cannot average complex values. Please apply a measure to the values before calling this function.');
        return;
    end
    % Average time-freq values
    TimefreqMat.TF = mean(TimefreqMat.TF, 3);
    % Remove the frequency information
    if iscell(TimefreqMat.Freqs)
        TimefreqMat.Freqs = {'Avg freq', TimefreqMat.Freqs{1,2}, TimefreqMat.Freqs{end,3}};
    else
        TimefreqMat.Freqs = TimefreqMat.Freqs(end);
    end
    % Do not keep the Std field in the output
    if isfield(TimefreqMat, 'Std') && ~isempty(TimefreqMat.Std)
        TimefreqMat.Std = [];
    end
    % TFmask: Keep only the values good everywhere
    if isfield(TimefreqMat, 'TFmask') && ~isempty(TimefreqMat.TFmask)
        TimefreqMat.TFmask = all(TimefreqMat.TFmask, 1);
    end

    % Add file tag
    TimefreqMat.Comment = [TimefreqMat.Comment, ' | avgfreq'];
    % Add history entry
    TimefreqMat = bst_history('add', TimefreqMat, 'avgfreq', 'Averaged all the frequency bands.');

    % Overwrite the input file
    if isOverwrite
        OutputFile = file_fullpath(sInput.FileName);
        bst_save(OutputFile, TimefreqMat, 'v6');
        % Reload study
        db_reload_studies(sInput.iStudy);
    % Save new file
    else
        % Output filename: add file tag
        OutputFile = strrep(file_fullpath(sInput.FileName), '.mat', '_avgfreq.mat');
        OutputFile = file_unique(OutputFile);
        % Save file
        bst_save(OutputFile, TimefreqMat, 'v6');
        % Add file to database structure
        db_add_data(sInput.iStudy, OutputFile, TimefreqMat);
    end
end


function spectra = loadallspectra(file)
% load all spectra files of a Dubna meassurement cycle
%
% Input
%  filename -
%
% Output
%  spectra - []
%

dir = file(1:max(strfind(file,'/')));
maxrot = findmax(dir);
fprintf('load detector: ');

for det=1:19
	fprintf([char(96+det),', ']);

	for rot=0:maxrot

		s = int2str(rot);
		if rot<10, s = ['0',s];end %#ok<AGROW>

		spec = loadspectra([file,'.',char(96+det),s]);
		if ~isempty(spec),  spectra(:,rot+1,det)=spec;end %#ok<AGROW>
	end
end
disp('.');

function m = findmax(directory)

l = dir(directory);
if isempty(l), error('directory not found or empty');end
for i=3:length(l), m(i-2) = max([0,str2num(l(i).name(end-1:end))]);end %#ok<ST2NM,AGROW>
m = max(m);


function trials = er_assignColors(trials);
%
% trials = er_assignColors(trials);
%
% Dialog to assign colors to different conditions for
% event-related analyses.
%
% written by ras, 09/2005
if ieNotDefined('trials')
    trials = er_concatParfiles(getSelectedInplane);
end

% set up an input dialog to get colors %%%%%%%%%%%%%%%%%%%
dlg(1).fieldName = 'preset';
dlg(1).style = 'popup';
dlg(1).string = 'Use a preset color map?';
dlg(1).list = {'No, manually define below...'};
dlg(1).value = 1;
presets = mrvColorMaps;
for i = 1:length(presets), dlg(1).list{i+1} = presets{i}; end

for i = 1:length(trials.condNums)
    dlg(i+1).fieldName = sprintf('Cond%i',i);
    dlg(i+1).style = 'edit';
    dlg(i+1).string = sprintf('%s color', trials.condNames{i});
    dlg(i+1).value = num2str(trials.condColors{i});
end

resp = generalDialog(dlg, 'Set Cond Colors...');

% exit quietly if user cancels
if isempty(resp), return; end

preset = cellfind(dlg(1).list, resp.preset);
if preset>1
    % use preset value
    map = mrvColorMaps(preset-1, length(trials.condNums));
    for i = 1:size(map,1)
        trials.condColors{i} = map(i,:);
    end
else
    % parse the rest of the responses for manual definitions
    for i = 1:length(trials.condNums)
        field = sprintf('Cond%i',i);
        vals = sscanf(resp.(field),'%f %f %f');
        trials.condColors{i} = vals';
    end
end

return


function[]=inticks
%INTICKS  Sets the 'tickdir' property of the current axis to 'in'.
%   _________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2004--2015 J.M. Lilly --- type 'help jlab_license' for details
set(gca,'tickdir','in')


%%
% Get input file without braces.
% Outputs grid info:
params = read_input_file('input2d.IB2D');
Nx = params{find(strcmp({params{:,1}},'Nx')),2}
Ny = params{find(strcmp({params{:,1}},'Ny')),2}
Lx = params{find(strcmp({params{:,1}},'Lx')),2}
Ly = params{find(strcmp({params{:,1}},'Ly')),2}
supp = params{find(strcmp({params{:,1}},'supp')),2}
d_springs = params{find(strcmp({params{:,1}},'damped_springs')),2}
str_name = params{find(strcmp({params{:,1}},'string_name')),2}

params

%%
% Get input file with braces.
% Outputs grid info
params = read_input_file('input2d.IB2D');
grid_Info = params{find(strcmp({params{:,1}},'GridParameters')),2}

grid_Info


% from DNG to sRGB
filename = fullfile('data', '0001_DSC_9315.DNG');
[im_raw, metadata] = Load_Data_and_Metadata_from_DNG(filename);
im_srgb = run_pipeline(im_raw, metadata, 'raw', 'srgb');
imwrite(im_srgb, fullfile('data', 'im_srgb_1.png'));

% from normalized RAW to sRGB
im_norm = load(fullfile('data', '0001_NOISY_RAW_001.MAT'));
im_norm = im_norm.x;
metadata = load(fullfile('data', '0001_METADATA_RAW_001.MAT'));
metadata = metadata.metadata;
im_srgb = run_pipeline(im_norm, metadata, 'normal', 'srgb');
imwrite(im_srgb, fullfile('data', 'im_srgb_2.png'));


%Author: Yong Yuan;
%Homepage: yongyuan.name

% load cifar-10 dataset
load cifar-10-batches-mat/data_batch_1.mat;
data1=data;
labels1=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_2.mat;
data2=data;
labels2=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_3.mat;
data3=data;
labels3=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_4.mat;
data4=data;
labels4=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_5.mat;
data5=data;
labels5=labels;
clear data labels;
load cifar-10-batches-mat/test_batch.mat;
data6=data;
labels6=labels;
clear data labels;
database = [data1 labels1; data2 labels2; data3 labels3; data4 labels4; data5 labels5; data6 labels6];
cifar10labels = [labels1; labels2; labels3;labels4; labels5; labels6];

%method = 'show-in-random';
method = 'show-in-class';

switch(method)
    %% sort in class
    case 'show-in-class'
        [sortedLabels, index] = sort(cifar10labels);
        dataInClass = database(index, :);
        clear database;
        numShow = 100;
        numInRow = 10;
        numPerClass = 6000;
        I2 = uint8(zeros(33, 33, 3, numShow)); % 32 and 32 are the size of the output image
        for i=1:numInRow
            randID = randi(numPerClass, numInRow, 1);
            index = randID + (i-1)*numPerClass;
            for j=1:length(index)
                image_r=dataInClass(index(j,:),1:1024);
                image_g=dataInClass(index(j,:),1025:2048);
                image_b=dataInClass(index(j,:), 2049:end-1);
                image_rer = reshape(image_r, 32, 32);
                image_rer(:, end+1) = zeros(length(image_rer), 1);
                image_rer(end+1, :) = zeros(1,length(image_rer));
                image_reg = reshape(image_g, 32, 32);
                image_reg(:, end+1) = zeros(length(image_reg), 1);
                image_reg(end+1, :) = zeros(1,length(image_reg));
                image_reb = reshape(image_b, 32, 32);
                image_reb(:, end+1) = zeros(length(image_reb), 1);
                image_reb(end+1, :) = zeros(1,length(image_reb));
                image(:, :,1) = image_rer';
                image(:, :, 2) = image_reg';
                image(:, :, 3) = image_reb';
                image = uint8(image);
                I2(:, :, :, j+(i-1)*numInRow) = image;
            end
        end
        figure('Color', [1 1 1]); hold on;
        montage(I2(:, :, :, :));

    %% sort in random
    case 'show-in-random'
        numInColum = 100;
        numInRow = 100;
        numImg = 60000;
        I2 = uint8(zeros(32, 32, 3, numInRow*numInColum)); % 32 and 32 are the size of the output image
        randID = randi(numImg, numInRow*numInColum, 1);
        for i=1:numInRow
            for j=1:numInColum
                % sort with random
                image_r=database(randID(j+(i-1)*numInColum,:),1:1024);
                image_g=database(randID(j+(i-1)*numInColum,:),1025:2048);
                image_b=database(randID(j+(i-1)*numInColum,:), 2049:end-1);

                image_rer=reshape(image_r, 32, 32);
                image_reg=reshape(image_g, 32, 32);
                image_reb=reshape(image_b, 32, 32);
                image(:, :,1)=image_rer';
                image(:, :, 2)=image_reg';
                image(:, :, 3)=image_reb';
                image=uint8(image);
                I2(:, :, :, j+(i-1)*numInColum) = image;
            end
        end
        figure('Color', [1 1 1]); hold on;
        montage(I2(:, :, :, :));
end