function [filt, B, A] = ft_preproc_highpassfilter(dat, Fs, Fhp, N, type, dir, instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt)

% FT_PREPROC_HIGHPASSFILTER applies a high-pass filter to the data and thereby removes
% the low frequency components in the data
%
% Use as
%   [filt] = ft_preproc_highpassfilter(dat, Fsample, Fhp, N, type, dir, instabilityfix)
% where
%   dat             data matrix (Nchans X Ntime)
%   Fs              sampling frequency in Hz
%   Fhp             filter frequency in Hz
%   order           optional filter order, default is 6 (but) or dependent on frequency band and data length (fir/firls)
%   type            optional filter type, can be
%                     'but'       Butterworth IIR filter (default)
%                     'firws'     FIR filter with windowed sinc
%                     'fir'       FIR filter using MATLAB fir1 function
%                     'firls'     FIR filter using MATLAB firls function (requires MATLAB Signal Processing Toolbox)
%                     'brickwall' frequency-domain filter using forward and inverse FFT
%   dir             optional filter direction, can be
%                     'onepass'                   forward filter only
%                     'onepass-reverse'           reverse filter only, i.e. backward in time
%                     'onepass-zerophase'         zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only)
%                     'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation
%                     'onepass-minphase'          minimum-phase converted forward filter (non-linear, only for firws)
%                     'twopass'                   zero-phase forward and reverse filter (default, except for firws)
%                     'twopass-reverse'           zero-phase reverse and forward filter
%                     'twopass-average'           average of the twopass and the twopass-reverse
%   instabilityfix  optional method to deal with filter instabilities
%                     'no'       only detect and give error (default)
%                     'reduce'   reduce the filter order
%                     'split'    split the filter in two lower-order filters, apply sequentially
%   df              optional transition width (firws)
%   wintype         optional window type (firws), can be
%                     'hamming' (default)    maximum passband deviation 0.0022 [0.22%], stopband attenuation -53dB
%                     'hann'                 maximum passband deviation 0.0063 [0.63%], stopband attenuation -44dB
%                     'blackman'             maximum passband deviation 0.0002 [0.02%], stopband attenuation -74dB
%                     'kaiser'
%   dev             optional max passband deviation/stopband attenuation (only for firws with kaiser window, default = 0.001 [0.1%, -60 dB])
%   plotfiltresp    optional, 'yes' or 'no', plot filter responses (only for firws, default = 'no')
%   usefftfilt      optional, 'yes' or 'no', use fftfilt instead of filter (only for firws, default = 'no')
%
% Note that a one- or two-pass filter has consequences for the strength of the filter,
% i.e. a two-pass filter with the same filter order will attenuate the signal twice as
% strong.
%
% Further note that the filter type 'brickwall' filters in the frequency domain,
% but may have severe issues. For instance, it has the implication that the time
% domain signal is periodic. Another issue pertains to that frequencies are
% not well defined over short time intervals; particularly for low frequencies.
%
% See also PREPROC

% Copyright (c) 2003-2022, Robert Oostenveld, Arjen Stolk, Andreas Widmann,
% Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% determine the size of the data
[nchans, nsamples] = size(dat);

% set the default filter order later
if nargin<4 || isempty(N)
  N = [];
end

% set the default filter type
if nargin<5 || isempty(type)
  type = 'but';
end

% set the default filter direction
if nargin<6 || isempty(dir)
  if strcmp(type, 'firws')
    dir = 'onepass-zerophase';
  else
    dir = 'twopass';
  end
end

% set the default method to deal with filter instabilities
if nargin<7|| isempty(instabilityfix)
  instabilityfix = 'no';
end

% Set default transition width later
if nargin < 8 || isempty(df)
  df = [];
end

% Set default window type
if nargin < 9 || isempty(wintype)
  wintype = 'hamming';
end

% Set default passband deviation/stopband attenuation for Kaiser window
if nargin < 10 || isempty(dev)
  if strcmp(wintype, 'kaiser')
    dev = 0.001;
  else
    dev = [];
  end
end

% Set default passband deviation/stopband attenuation for Kaiser window
if nargin < 11 || isempty(plotfiltresp)
  plotfiltresp = 'no';
end

% Set default filter function
if nargin < 12 || isempty(usefftfilt)
  usefftfilt = false;
else
  % convert to boolean value
  usefftfilt = istrue(usefftfilt);
end

% Filtering does not work on integer data
if ~isa(dat, 'double') && ~isa(dat, 'single')
  dat = cast(dat, 'double');
end

% preprocessing fails on channels that contain NaN
if any(isnan(dat(:)))
  ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');
end

% Nyquist frequency
Fn = Fs/2;

% demean the data before filtering
meandat = nanmean(dat,2);
dat = bsxfun(@minus, dat, meandat);

% compute filter coefficients
switch type
  case 'but'
    if isempty(N)
      N = 6;
    end
    [B, A] = butter(N, max(Fhp)/Fn, 'high');

  case 'firws'
    % Input arguments
    if length(Fhp) ~= 1
      ft_error('One cutoff frequency required.')
    end

    % Filter order AND transition width set?
    if ~isempty(N) && ~isempty(df)
      ft_warning('firws:dfOverridesN', 'Filter order AND transition width set - transition width setting will override filter order.')
    elseif isempty(N) && isempty(df) % Default transition width heuristic
      df = fir_df(Fhp, Fs);
    end

    % Compute filter order from transition width
    [foo, maxDf] = fir_df(Fhp, Fs); %#ok<ASGLU>
    isOrderLow = false;
    if ~isempty(df)
      if df > maxDf
        ft_error('Transition band too wide. Maximum transition width is %.2f Hz.', maxDf)
      end
      [N, dev] = firwsord(wintype, Fs, df, dev);
    else % Check filter order otherwise
      [df, dev] = invfirwsord(wintype, Fs, N, dev);
      if df > maxDf
        nOpt = firwsord(wintype, Fs, maxDf, dev);
        ft_warning('firws:filterOrderLow', 'Filter order too low. For better results a minimum filter order of %d is recommended. Effective cutoff frequency might deviate from requested cutoff frequency.', nOpt)
        isOrderLow = true;
      end
    end

    % Window
    if strcmp(wintype, 'kaiser')
      beta = kaiserbeta(dev);
      win = windows('kaiser', N + 1, beta);
    else
      win = windows(wintype, N + 1);
    end

    % Impulse response
    B = firws(N, Fhp / Fn, 'high', win);
    A = 1;

    % Convert to minimum phase
    if strcmp(dir, 'onepass-minphase')
      B = minphaserceps(B);
    end

    % Twopass filtering
    if strncmp(dir, 'twopass', 7)
      pbDev = (dev + 1)^2 - 1;
      sbAtt = 20 * log10(dev^2);
      order = 2 * (length(B) - 1);
      isTwopass = true;
    else
      pbDev = dev;
      sbAtt = 20 * log10(dev);
      order = length(B) - 1;
      isTwopass = false;
    end

    % Reporting
    ft_info once
    ft_info('Highpass filtering data: %s, order %d, %s-windowed sinc FIR\n', dir, order, wintype);
    if ~isTwopass && ~isOrderLow % Do not report shifted cutoffs
      ft_info('  cutoff (-6 dB) %g Hz\n', Fhp);
      tb = [max([Fhp - df / 2 0]), min([Fhp + df / 2 Fn])]; % Transition band edges
      ft_info('  transition width %.1f Hz, stopband 0-%.1f Hz, passband %.1f-%.0f Hz\n', df, tb, Fn);
    end
    if ~isOrderLow
      ft_info('  maximum passband deviation %.4f (%.2f%%), stopband attenuation %.0f dB\n', pbDev, pbDev * 100, sbAtt);
    end

  case 'fir'
    if isempty(N)
      N = 3*fix(Fs / Fhp);
      if rem(N,2)==1,   N=N+1;    end
    end
    if N > floor( (size(dat,2) - 1) / 3)
      N=floor(size(dat,2)/3) - 2;
      if rem(N,2)==1,   N=N+1;    end
    end
    B = fir1(N, max(Fhp)/Fn, 'high');
    A = 1;

  case 'firls' % from NUTMEG's implementation
    % Deprecated: see bug 2453
    ft_warning('The filter type you requested is not recommended for neural signals, only proceed if you know what you are doing.')
    if isempty(N)
      N = 3*fix(Fs / Fhp);
      if rem(N,2)==1,   N=N+1;    end
    end
    if N > floor( (size(dat,2) - 1) / 3)
      N=floor(size(dat,2)/3) - 2;
      if rem(N,2)==1,   N=N+1;    end
    end
    f = 0:0.001:1;
    if rem(length(f),2)~=0
      f(end)=[];
    end
    z = zeros(1,length(f));
    [val,pos1] = min(abs(Fs*f/2 - Fhp));
    pos2 = length(f);
    z(pos1:pos2) = 1;
    A = 1;
    B = firls(N,f,z); % requires MATLAB signal processing toolbox

  case 'brickwall'
    ax = (0:(size(dat,2)-1))./(Fs/size(dat,2)); % frequency axis

    a     = ones(1, size(dat,2));
    fbin1 = nearest(ax, Fhp);
    fbin2 = nearest(ax, Fs-Fhp);

    a(1:(fbin1-1))   = 0;
    a((fbin2+1):end) = 0;

    f    = fft(dat,[],2);             % FFT
    f    = f.*a(ones(size(dat,1),1),:); % brickwall
    filt = real(ifft(f,[],2));        % iFFT

  otherwise
    ft_error('unsupported filter type "%s"', type);
end

% Plot filter responses
if strcmp(plotfiltresp, 'yes')
  plotfresp(B, A, [], Fs, dir)
end

if ~isequal(type, 'brickwall')
  try
    filt = filter_with_correction(B,A,dat,dir,usefftfilt);
  catch
    switch instabilityfix
      case 'no'
        rethrow(lasterror);
      case 'reduce'
        ft_warning('off','backtrace');
        ft_warning('filter instability detected - reducing the %dth order filter to an %dth order filter', N, N-1);
        ft_warning('on','backtrace');
        filt = ft_preproc_highpassfilter(dat,Fs,Fhp,N-1,type,dir,instabilityfix);
      case 'split'
        N1 = ceil(N/2);
        N2 = floor(N/2);
        ft_warning('off','backtrace');
        ft_warning('filter instability detected - splitting the %dth order filter in a sequential %dth and a %dth order filter', N, N1, N2);
        ft_warning('on','backtrace');
        filt = ft_preproc_highpassfilter(dat ,Fs,Fhp,N1,type,dir,instabilityfix);
        filt = ft_preproc_highpassfilter(filt,Fs,Fhp,N2,type,dir,instabilityfix);
      otherwise
        ft_error('incorrect specification of instabilityfix');
    end % switch
  end
end


function results = vl_test_ikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;

function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;

function test_basic(s)
[centers, assign] = vl_ikmeans(s.data,100) ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;

function test_elkan(s)
[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;


function [params, runConfig] = readConfig(yaml_file)

configs = ReadYaml(yaml_file);
names = fieldnames(configs);
num = length(names);

for i=1:num
    if strcmp(names{i}, 'runConfigs')
        runConfig = getfield(configs, names{i});
        names = [names(1:i-1), names(i+1:end)];
        break;
    end
end

num = length(names);
param_bounds = zeros(num, 2);
discrete_indices = zeros(0, 0);
log_indices = zeros(0, 0);
categorical_indices = zeros(0, 0);
for i=1:num
    field = getfield(configs, names{i});
    param_bounds(i, 1) = field.lowerbound;
    param_bounds(i, 2) = field.upperbound;

    if isfield(field, 'integer') && field.integer
        discrete_indices(length(discrete_indices)+1) = i;
    end

    if isfield(field, 'categorical') && field.categorical
        categorical_indices(length(categorical_indices)+1) = i;
    end

    if isfield(field, 'logscale') && field.logscale
        log_indices(length(log_indices)+1) = i;
    end
end

param_bounds(log_indices, :) = log(param_bounds(log_indices, :));

params.high_dim = size(param_bounds, 1);
params.param_bounds = param_bounds';
params.log_indices = log_indices;
params.discrete_indices = discrete_indices;
params.categorical_indices = categorical_indices;
params.param_range = params.param_bounds(2, :) - params.param_bounds(1, :);
params.param_range(discrete_indices) = params.param_range(discrete_indices) + 1;
params.param_bounds(1, discrete_indices) = ...
    params.param_bounds(1, discrete_indices) - 0.5;

end


function net = vgg_s(labelNum,lossWeight,opts)
channel_num=512;
mag=0.1;
netname='vgg-s';

partRate=1;
textureRate=0;
output_num=labelNum;
net=load('../nets/imagenet-vgg-s.mat');

net.layers=net.layers(1:end-7);
net.layers{end-1}.learningRate=[1,5];
net=add_block_mask(net,lossWeight, opts,'6',3,3,512,channel_num,1,1,partRate,textureRate,mag); %%%%%%%%%%%%%%%%%
net.layers{end+1} = struct('type', 'pool', 'name', 'pool6', ...
                           'method', 'max', ...
                           'pool', [3 3], ...
                           'stride', 3, ...
                           'pad', [0 1 0 1]) ;
net=add_block_mask(net,lossWeight,opts,'7',6,6,channel_num,4096,1,0,partRate,textureRate,mag); %%%%%%%%%%%%%%%%%

net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '8') ;

net = add_block(net, opts, '9', 1, 1, 4096, output_num, 1, 0) ;
net.layers(end) = [] ;
net.meta.classes.name={'pos'};
net.meta.classes.description={'pos'};
net.meta.normalization.imageSize=net.meta.normalization.imageSize(1:3);
net.meta.netname=netname;
end


function [x_out] = applyBeamforming(arraySignal, dMic, fs, DOA, typeBF, flagGSC)

nChannels = size(arraySignal,1);
x = arraySignal;  % input signal, matrix  [nChannels * time]

%=========initialize parameters for spectral processing ===================%
len=floor(20 * fs / 1000); % Frame size in samples
if rem(len,2)==1,
    len=len+1;
end;
overlap = 0.50; % window overlap in percent of frame size
len1 = floor(len * overlap);
len2 = len - len1;

nFrames = floor(size(x, 2)/len2) - floor(len/len2);
xfinal = zeros(1, nFrames*len2+len1);

win = hamming(len)';  % define window
win2D = repmat(win, nChannels, 1);

nFFT = len;
f = linspace(0, fs, nFFT);% freqeuncy vector
%==========================================================================%

%============================Initialize covariance matirx==================%
noise_mean=zeros(nChannels, nFFT);
noiseConv = zeros(nChannels, nChannels, nFFT);
j=1;
for k=1:10   %use fisrt 10 segments to  estimate noise spectrum
    noise_spec = fft(win2D .* x(:, j:j+len-1), nFFT, 2);
    noise_mean = noise_mean + noise_spec;
    for freqidx = 1:nFFT
        noiseConv(:,:,freqidx) = noiseConv(:,:,freqidx) + (noise_spec(:, freqidx)' * noise_spec(:, freqidx));
    end
    j = j + len2;
end
noiseConv = noiseConv / 10;
%==========================================================================%

%================= generate beamformer ====================================%
hw = zeros(nChannels, nFFT);
if strcmp(typeBF, 'DSB')
    hw = dsb(nChannels, dMic, DOA, f);        % delay-and-sum filter
elseif  strcmp(typeBF, 'MVDR')
    hw = mvdrFF(nChannels, dMic, DOA, f, noiseConv);
end
%==========================================================================%

%================= speech enhancement per frame============================%
k = 1;
for n = 1 : nFrames

    xk = win2D .* x(:, k:k+len-1);
    spec = fft(xk, nFFT, 2);

    %vad or speech presence probability
    %power covariance matrix
    %updatebeamformer
    %rtf = rtf(, noiseConv)
    %hw = mvdr(rtf, noiseConv);

    if flagGSC == false
        spec_bf = sum(hw .* spec, 1);
    else
        [spec_bf, ak] = lmsGSC(X(:, 1:(L/2)+1), hw, 0, B, ak, mu);
    end

    xi_w = ifft( spec_bf, nFFT);
    xi_w = real(xi_w);

   % Overlap and add
    xfinal( k:k+len-1) =  xfinal(k:k+len-1) + win.* xi_w;

    k = k + len2;

end
%==========================================================================%

%===============================Output=====================================%
x_out = xfinal;
%==========================================================================%

end


classdef LHSintegrator_DiffReactNeumann < handle

    properties (GetAccess = public, SetAccess = private)
        M
        K
    end

    properties (Access = private)
        mesh
    end

    methods (Access = public)

        function obj = LHSintegrator_DiffReactNeumann(cParams)
            obj.mesh  = cParams.mesh;
            obj.computeStiffnessMatrix(cParams);
            obj.computeMassMatrix();
        end

        function LHS = compute(obj, epsilon)
            LHS = epsilon^2*obj.K + obj.M;
        end

    end

    methods (Access = private)

        function computeStiffnessMatrix(obj,cParams)
            s      = cParams;  % For anisotropic stiffness
            s.type = cParams.stiffType;
            s.mesh = obj.mesh;
            s.fun  = P1Function.create(obj.mesh,1);
            LHS    = LHSintegrator.create(s);
            obj.K  = LHS.compute();
        end

        function computeMassMatrix(obj)
            s.type  = 'MassMatrix';
            s.mesh  = obj.mesh;
            s.fun  = P1Function.create(obj.mesh, 1);
            s.quadratureOrder = 'QUADRATICMASS';
            LHS     = LHSintegrator.create(s);
            obj.M   = LHS.compute();
        end

    end

end


% DEMOILLLE4 Demonstrate LLE on the oil data.

% MLTOOLS

[Y, lbls] = lvmLoadData('oil');

options = lleOptions(32, 2);
model = lleCreate(2, size(Y, 2), Y, options);
model = lleOptimise(model);

lvmScatterPlot(model, lbls);

if exist('printDiagram') & printDiagram
  lvmPrintPlot(model, lbls, 'Oil', 4);
end

errors = lvmNearestNeighbour(model, lbls);


function cp_values_test ( )

%*****************************************************************************80
%
%% CP_VALUES_TEST demonstrates the use of CP_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CP_VALUES_TEST:\n' );
  fprintf ( 1, '  CP_VALUES stores values of\n' );
  fprintf ( 1, '  the specific heat CP\n' );
  fprintf ( 1, '  as a function of temperature and pressure.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      T            P            CP(T,P)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, tc, p, cp ] = cp_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %12f  %12f  %24.16f\n', tc, p, cp );

  end

  return
end


function [ indx, i, j ] = sort_heap_external ( n, indx, isgn )

%*****************************************************************************80
%
%% SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.
%
%  Discussion:
%
%    The actual list of data is not passed to the routine.  Hence this
%    routine may be used to sort integers, reals, numbers, names,
%    dates, shoe sizes, and so on.  After each call, the routine asks
%    the user to compare or interchange two items, until a special
%    return value signals that the sorting is completed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 February 2010
%
%  Author:
%
%    Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    Albert Nijenhuis, Herbert Wilf.
%    Combinatorial Algorithms,
%    Academic Press, 1978, second edition,
%    ISBN 0-12-519260-6.
%
%  Parameters:
%
%    Input, integer N, the number of items to be sorted.
%
%    Input, integer INDX, the main communication signal.
%    The user must set INDX to 0 before the first call.
%    Thereafter, the user should set the input value of INDX
%    to the output value from the previous call.
%
%    Input, integer ISGN, results of comparison of elements I and J.
%    (Used only when the previous call returned INDX less than 0).
%    ISGN <= 0 means I is less than or equal to J;
%    0 <= ISGN means I is greater than or equal to J.
%
%    Output, integer INDX, the main communication signal.
%    If INDX is
%
%      greater than 0, the user should:
%      * interchange items I and J;
%      * call again.
%
%      less than 0, the user should:
%      * compare items I and J;
%      * set ISGN = -1 if I < J, ISGN = +1 if J < I;
%      * call again.
%
%      equal to 0, the sorting is done.
%
%    Output, integer I, J, the indices of two items.
%    On return with INDX positive, elements I and J should be interchanged.
%    On return with INDX negative, elements I and J should be compared, and
%    the result reported in ISGN on the next call.
%
  persistent i_save;
  persistent j_save;
  persistent k;
  persistent k1;
  persistent n1;

  if ( isempty ( i_save ) )
    i_save = -1;
  end

  if ( isempty ( j_save ) )
    j_save = -1;
  end
%
%  INDX = 0: This is the first call.
%
  if ( indx == 0 )

    k = floor ( n / 2 );
    k1 = k;
    n1 = n;
%
%  INDX < 0: The user is returning the results of a comparison.
%
  elseif ( indx < 0 )

    if ( indx == -2 )

      if ( isgn < 0 )
        i_save = i_save + 1;
      end

      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    end

    if ( 0 < isgn )
      indx = 2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )

      if ( n1 == 1 )
        i_save = 0;
        j_save = 0;
        indx = 0;
      else
        i_save = n1;
        n1 = n1 - 1;
        j_save = 1;
        indx = 1;
      end

      i = i_save;
      j = j_save;
      return;

    end

    k = k - 1;
    k1 = k;
%
%  0 < INDX, the user was asked to make an interchange.
%
  elseif ( indx == 1 )

    k1 = k;

  end

  while ( 1 )

    i_save = 2 * k1;

    if ( i_save == n1 )
      j_save = k1;
      k1 = i_save;
      indx = -1;
      i = i_save;
      j = j_save;
      return;
    elseif ( i_save <= n1 )
      j_save = i_save + 1;
      indx = -2;
      i = i_save;
      j = j_save;
      return;
    end

    if ( k <= 1 )
      break;
    end

    k = k - 1;
    k1 = k;

  end

  if ( n1 == 1 )
    i_save = 0;
    j_save = 0;
    indx = 0;
    i = i_save;
    j = j_save;
  else
    i_save = n1;
    n1 = n1 - 1;
    j_save = 1;
    indx = 1;
    i = i_save;
    j = j_save;
  end

  return
end


function [SuperFibersGroup, IDsOfFlipped, startCoords, endCoords]=dtiReorientSuperfiberGroups(SuperFibersGroup)

%Given a set of superfiber groups across the participants, checks that all start points and all end points are
%grouped respectively. Flip some groups if needed. Returned all the
%superfibers (including the reoriented ones) and a vector with "1" for
%groups which had to be reoriented (first node -> last)

%Input: 1xX array of SuperFibersGroup
%ER wrote it 08/10/2009
numsubjects=length(SuperFibersGroup);
IDsOfFlipped=[];
for s=1:numsubjects
numNodes(s)=size(SuperFibersGroup(s).fibers{1}, 2);
end

if length(unique(numNodes))>1
    error ('need to have the same number of nodes in each superfibergroup');
end

curves=zeros(3, unique(numNodes), numsubjects);
for i=1:numsubjects
    curves(:, :, i)=SuperFibersGroup(i).fibers{1};
end

%Check that the all the starting points and all the end points are grouped.
%Flip the fibers whose end point groups with the starting points of the
%other.
T = clusterdata([squeeze(curves(:, 1, :))'; squeeze(curves(:, end, :))'], 'maxclust', 2);
Tstart=T(1:end/2); Tend=T(end/2+1:end);

%Take first and last points in every fibers and cluster together. The two
%clouds should be quite separate for a tract with distinct termination
%ROIs. Looking at the labels for the start points, keep fibers
%corresponding to classlabel=1 intact. Swap the node order for the fibers
%corresponding to classlabel=2;
if ~(sum(Tstart==2)==numsubjects | sum(Tstart==1)==numsubjects)
curves(:, :, Tstart==2)=flipdim(curves(:, :, Tstart==2), 2);
display(['Flipped ' num2str(sum(Tstart==2)) ' superfibers of ' num2str(numsubjects)]);
IDsOfFlipped=Tstart==2;
end

startCoords=zeros(3, 1);
endCoords=zeros(3, 1);

for i=1:numsubjects
SuperFibersGroup(i).fibers{1}= curves(:, :, i);
startCoords=startCoords+SuperFibersGroup(i).fibers{1}(:, 1);
endCoords=endCoords+SuperFibersGroup(i).fibers{1}(:, end);
end

startCoords=startCoords./numsubjects;
endCoords=endCoords./numsubjects;


function res = grs2rgb(img, map)

%%Convert grayscale images to RGB using specified colormap.
%	IMG is the grayscale image. Must be specified as a name of the image
%	including the directory, or the matrix.
%	MAP is the M-by-3 matrix of colors.
%
%	RES = GRS2RGB(IMG) produces the RGB image RES from the grayscale image IMG
%	using the colormap HOT with 64 colors.
%
%	RES = GRS2RGB(IMG,MAP) produces the RGB image RES from the grayscale image
%	IMG using the colormap matrix MAP. MAP must contain 3 columns for Red,
%	Green, and Blue components.
%
%	Example 1:
%	open 'image.tif';
%	res = grs2rgb(image);
%
%	Example 2:
%	cmap = colormap(summer);
% 	res = grs2rgb('image.tif',cmap);
%
% 	See also COLORMAP, HOT
%
%	Written by
%	Valeriy R. Korostyshevskiy, PhD
%	Georgetown University Medical Center
%	Washington, D.C.
%	December 2006
%
% 	vrk@georgetown.edu

% Check the arguments
if nargin<1
	error('grs2rgb:missingImage','Specify the name or the matrix of the image');
end;

if ~exist('map','var') || isempty(map)
	map = hot(64);
end;

[l,w] = size(map);

if w~=3
	error('grs2rgb:wrongColormap','Colormap matrix must contain 3 columns');
end;

if ischar(img)
	a = imread(img);
elseif isnumeric(img)
	a = img;
else
	error('grs2rgb:wrongImageFormat','Image format: must be name or matrix');
end;

% Calculate the indices of the colormap matrix
a = double(a);
a(a==0) = 1; % Needed to produce nonzero index of the colormap matrix
ci = ceil(l*a/max(a(:)));

% Colors in the new image
[il,iw] = size(a);
r = zeros(il,iw);
g = zeros(il,iw);
b = zeros(il,iw);
r(:) = map(ci,1);
g(:) = map(ci,2);
b(:) = map(ci,3);

% New image
res = zeros(il,iw,3);
res(:,:,1) = r;
res(:,:,2) = g;
res(:,:,3) = b;


function u = cos(a)
%COS          Slope cosine cos(a)
%

% written  12/06/98     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  INTLAB_SLOPE = getappdata(0,'INTLAB_SLOPE');

  u = a;

  u.r = cos(a.r);
  indexc = 1:INTLAB_SLOPE.NUMVAR;
  indexr = 2:INTLAB_SLOPE.NUMVAR+1;
  Xxs = hull(a.r(:,indexc),a.r(:,indexr));
  u.s = - sin(Xxs) .* a.s;

  if rndold
    setround(rndold)
  end


function element_size = p11_element_size ( )

%*****************************************************************************80
%
%% P11_ELEMENT_SIZE returns a typical element size for problem 11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real ELEMENT_SIZE, a typical element size.
%
  element_size = 0.15;

  return
end


helpdlg('SEISMOLAP is no longer supported as a part of ZMAP. Please contact  Prof. J. Zschau , GFZ Potsdam, zschau@gzf-potsdam.de, for information on recent SeismoLap implementations')

report_this_filefun(mfilename('fullpath'));

return

ttlStr='  Introduction to Seismo Lap in ZMAP';
hlpStr= ...
    ['                                                                             '
    ' SeismoLap is a technique develloped by J. Zschau                            '
    ' (Geoforschungzentrum Potsdam, Germany) to measure the relative              '
    ' seismic activity in an area. The space-time overlap of cubical              '
    ' volumes is measured, normalized by the size of the cube (SeismoLap1)        '
    ' The negaite invers of this value Seismolap2 is calculated and the           '
    ' probabilty estimated using a Pearson type 3 distribution.                   '
    '                                                                             '
    ' The ZMAP implementation of SeismoLap offers the following options:          '
    '                                                                             '
    ' One point calculation: SeismoLap1 and the probability can be calculated     '
    '     at one point in space. It is nessesary to define the Input paramters    '
    '     lat/long of the point of interest, box siz, and interaction time.       '
    '  Grid: Both the seismolap 1 and probability values can be calculated        '
    '       using a grid of points. At each grid-point the time series            '
    '       is calcualted and the user can view different time cuts in a color    '
    '       representation. The time series at a user defined point can be viewed '
    '       by selecting the Mouse option. Since it take a while to               '
    '       calculate a grid, it is recommended to save the grid and re-load them '
    '       when desired.                                                         '
    ' Movie: A number of time cuts can be animated as a movie sequence.           '
    '        This movie file can be save and re-loaded.                           '
    '                                                                             '
    ' If   you have problems whith this software, please contact:                 '
    ' Stefan Wiemer                                                               '
    ' Geophysical Institute University of Alaska Fairbanks                        '
    ' Fairbanks, AK, 99775-7320, USA                                              '
    ' phone: 907 474 6171, Fax 907 474 7290                                       '
    ' e-mail stefan@giseis.alaska.edu                                             '
    '                                                                             '
    ' Enjoy!                                                                      '
    ' Stefan Wiemer   September . 95                                              '
    '                                                                             '];

zmaphelp(ttlStr,hlpStr)


function node_boundary = triangulation_order6_boundary_node ( node_num, ...
  triangle_num, triangle_node )

%*****************************************************************************80
%
%% TRIANGULATION_ORDER6_BOUNDARY_NODE indicates which nodes are on the boundary.
%
%  Discussion:
%
%    This routine is given an order 6 triangulation, an abstract list of sets
%    of six nodes.  The vertices are listed clockwise, then the
%    midside nodes.
%
%    It is assumed that each edge of the triangulation is either
%    * an INTERIOR edge, which is listed twice, once with positive
%      orientation and once with negative orientation, or;
%    * a BOUNDARY edge, which will occur only once.
%
%    This routine should work even if the region has holes - as long
%    as the boundary of the hole comprises more than 3 edges!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 June 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, integer TRIANGLE_NUM, the number of triangles.
%
%    Input, integer TRIANGLE_NODE(6,TRIANGLE_NUM), the nodes that make up the
%    triangles.
%
%    Output, logical NODE_BOUNDARY(NODE_NUM), is TRUE if the node
%    is on a boundary edge.
%
  m = 3;
  n = 3 * triangle_num;
%
%  Set up the edge array.  The midside node is listed last, as
%  it is not needed for the sorting process.
%
  edge(1,               1:  triangle_num) = triangle_node(1,1:triangle_num);
  edge(2,               1:  triangle_num) = triangle_node(4,1:triangle_num);
  edge(3,               1:  triangle_num) = triangle_node(2,1:triangle_num);

  edge(1,  triangle_num+1:2*triangle_num) = triangle_node(2,1:triangle_num);
  edge(2,  triangle_num+1:2*triangle_num) = triangle_node(5,1:triangle_num);
  edge(3,  triangle_num+1:2*triangle_num) = triangle_node(3,1:triangle_num);

  edge(1,2*triangle_num+1:3*triangle_num) = triangle_node(3,1:triangle_num);
  edge(2,2*triangle_num+1:3*triangle_num) = triangle_node(6,1:triangle_num);
  edge(3,2*triangle_num+1:3*triangle_num) = triangle_node(1,1:triangle_num);
%
%  In each column, force the smaller of the two vertices to appear first.
%
  e1(1:n) = min ( edge(1:2:3,1:n) );
  e2(1:n) = max ( edge(1:2:3,1:n) );

  edge(1,1:n) = e1(1:n);
  edge(3,1:n) = e2(1:n);
%
%  Ascending sort the column array.
%
  edge = ( sortrows ( edge' ) )';
%
%  Records which appear twice are internal edges and can be ignored.
%
  node_boundary(1:node_num) = 0;

  i = 0;

  while ( i < 3 * triangle_num )

    i = i + 1;

    if ( i == 3 * triangle_num )
      node_boundary(edge(1:m,i)) = 1;
    elseif ( all ( edge(1:m,i) == edge(1:m,i+1) ) )
      i = i + 1;
    else
      node_boundary(edge(1:m,i)) = 1;
    end

  end

  return
end


function [params, names] = matern32KernExtractParam(kern)

% MATERN32KERNEXTRACTPARAM Extract parameters from the MATERN32 kernel structure.
% FORMAT
% DESC extracts parameters from the matern kernel with nu=3/2
% kernel structure into a vector of parameters for optimisation.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel structure, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
%
% FORMAT
% DESC extracts parameters and parameter names from the matern kernel with nu=3/2
% kernel structure.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel structure, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
% RETURN names : cell array of strings containing names for each
% parameter.
%
% SEEALSO matern32KernParamInit, matern32KernExpandParam, kernExtractParam, scg, conjgrad
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% KERN

params = [kern.lengthScale kern.variance];
if nargout > 1
  names={'length scale', 'variance'};
end


%% Copyright (C) 2014, 2016, 2019 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty
%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
%% the GNU General Public License for more details.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym flipud (@var{A})
%% Flip a symbolic matrix vertically.
%%
%% Example:
%% @example
%% @group
%% A = sym([1 2 pi; 4 5 6]);
%% flipud (A)
%%   @result{} (sym 2×3 matrix)
%%       ⎡4  5  6⎤
%%       ⎢       ⎥
%%       ⎣1  2  π⎦
%% @end group
%% @end example
%%
%% @seealso{@@sym/fliplr, @@sym/reshape}
%% @end defmethod

function B = flipud (A)

  cmd = { 'A, = _ins'
          'if A is None or not A.is_Matrix:'
          '    A = sp.Matrix([A])'
          'return A[::-1, :]' };

  B = pycall_sympy__ (cmd, sym(A));

end

%!test
%! % simple
%! syms x
%! A = [x 2; sym(pi) x];
%! B = [sym(pi) x; x 2];
%! assert (isequal (flipud(A), B))

%!test
%! % simple, odd # rows
%! syms x
%! A = [x 2; sym(pi) x; [1 2]];
%! B = [[1 2]; sym(pi) x; x 2];
%! assert (isequal (flipud(A), B))

%!test
%! % scalar
%! syms x
%! assert (isequal (flipud(x), x))


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%        Sample Data and Metch Registration Sessions        %
%                                                           %
%           by Qianqian Fang <q.fang at neu.edu>            %
%                                                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% first of all, make sure you've already add the metch root
% folder to your matlab/octave search path list

% load the sample data, where
%   no: the node coordinates of a surface mesh
%   el: the surface triangles
%   pt: the point cloud to be registered

load sampledata

% start the metch-gui to perform the registration

%== Description of the workflow ==
%
% 1. when the GUI pops up, it will display the mesh and the points,
%    you can rotate both plots so that you can identify the matching
%    features
% 2. switch on "Select" mode, then, click on a land-mark point on the point
%    plot, when a data-tip shows up, click "Add Selected" button
% 3. click on the corresponding position on the mesh, and click
%    "Add Selected"
% 4. repeat the above for at least 4 point pairs (you can select more);
%    if you want to change views, switch off "Select" box and rotate;
%    after rotation, switch on "Select" box again
% 5. click "Initialize": this will create the initial mapping using the
%    selected point pairs
% 6. click "Optimize": this will fit the surface with the whole point cloud
% 7. click "Proj2Mesh": this will project the fitted point clouds onto the
%    mesh
% 8. you can quit the GUI by hit "Close", your results will be saved to reg
% 9. close the window

if(exist('OCTAVE_VERSION')~=0)
        reg=metchgui_one(no,el,pt);
else
        reg=metchgui(no,el,pt);
end


%  sandwich_solve solves the linear equation X=A*X*B+C
%
%  ::
%
%    [X,retcode]=sandwich_solve(A,B,C)
%
%  Args:
%     - A :
%     - B :
%     - C :
%
%  Returns:
%     :
%     - X :
%     - retcode :
%
%  Note:
%
%  Example:
%
%     See also:
%


function [ decision ] = face_check_cnn( img, shape, global_params, cnns )
%FACE_CHECK_CNN Summary of this function goes here
%   Detailed explanation goes here

%%
if(size(img,3) == 3)
    img = rgb2gray(img);
end
% first need to determine the view
centres = cat(1, cnns.centres);

dists = centres*pi/180 - repmat(global_params(2:4)',size(centres,1),1);
[~,view_id] = min(sum(dists.^2,2));

mask_small = cnns(view_id).mask(1:size(cnns(view_id).triX,1), 1:size(cnns(view_id).triX,2));

if(size(cnns(view_id).destination,1) == 66 && size(shape,1) == 68)
    label_inds = [1:60,62:64,66:68];
    shape = shape(label_inds,:);
end
img_crop = Crop(img, shape, cnns(view_id).triangulation,...
    cnns(view_id).triX, mask_small,...
    cnns(view_id).alphas, cnns(view_id).betas,...
    cnns(view_id).nPix, cnns(view_id).minX, ...
    cnns(view_id).minY);

%%
img_crop = reshape(img_crop(logical(cnns(view_id).mask)), 1, cnns(view_id).nPix);
img_crop(isnan(img_crop)) = 0;

% normalisation (local)
img_crop = (img_crop - mean(img_crop));
norms = std(img_crop);
if(norms==0)
    norms = 1;
end
img_crop = img_crop / norms;

% normalisation (global)
img_crop = img_crop - cnns(view_id).mean_ex;
img_crop = img_crop ./ cnns(view_id).std_ex;

mask = cnns(view_id).mask;

img = zeros(size(mask));
img(mask) = img_crop;

cnn = cnns(view_id).cnn;

%%
res = vl_simplenn(cnn, single(img), [], []);
res = gather(res(end).x);
num_bins = numel(res);
[~,res] = sort(res, 3, 'descend') ;
res = squeeze(res);
res = res(1,:);

decision = unQuantizeContinuous(res, 0, 3, num_bins)';


function van_der_corput_test04 ( )

%*****************************************************************************80
%
%% VAN_DER_CORPUT_TEST04 tests VAN_DER_CORPUT_SEQUENCE, VAN_DER_CORPUT_SEED_GET, VAN_DER_CORPUT_SEED_SET.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 February 2011
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'VAN_DER_CORPUT_TEST04\n' );
  fprintf ( 1, '  VAN_DER_CORPUT_BASE_SET sets the base;\n' );
  fprintf ( 1, '  VAN_DER_CORPUT_BASE_GET gets the base;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  In this test, we show how setting the base changes\n' );
  fprintf ( 1, '  the results of the sequence.\n' );
  fprintf ( 1, '\n' );

  seed = 0;
  van_der_corput_seed_set ( seed );

  base = 2;
  van_der_corput_base_set ( base );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Current SEED = %d\n', seed );
  fprintf ( 1, '  Current BASE = %d\n', base );

  n = 10;
  r = van_der_corput_sequence ( n );

  for i = 1: n
    fprintf ( 1, '%d %f\n', seed+i-1, r(i) );
  end

  seed = 0;
  van_der_corput_seed_set ( seed );

  base = 3;
  van_der_corput_base_set ( base );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Repeat the calculation with a new base.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Current SEED = %d\n', seed );
  fprintf ( 1, '  Current BASE = %d\n', base );

  seed = van_der_corput_seed_get ( );

  n = 10;
  r = van_der_corput_sequence ( n );

  for i = 1: n
    fprintf ( 1, '%d %f\n', seed+i-1, r(i) );
  end

  seed = 0;
  van_der_corput_seed_set ( seed );

  base = 4;
  van_der_corput_base_set ( base );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Repeat the calculation with a new base.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Current SEED = %d\n', seed );
  fprintf ( 1, '  Current BASE = %d\n', base );

  seed = van_der_corput_seed_get ( );

  n = 10;
  r = van_der_corput_sequence ( n );

  for i = 1: n
    fprintf ( 1, '%d %f\n', seed+i-1, r(i) );
  end

  return
end


function [ X ] = special_add_right_not( X,S )

    s_theta=S(1:3);
    s_p=S(4:6);

    sizeS=size(S,1);
    NumberOfLandmarks=(sizeS-6)/3;

    Exps=so3_exp(s_theta);

    X.position= Exps*X.position+jaco_r(-s_theta)*s_p;

    if NumberOfLandmarks>=1
        s_landmarksMatrix=reshape(S(7:end),3,NumberOfLandmarks);
        X.landmarks(1:3,:)=Exps*X.landmarks(1:3,:)+s_landmarksMatrix;
    end

    X.orientation=Exps*X.orientation;

end


classdef (Abstract) mme_branch_opf_ac < mp.mme_branch_opf

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

%     properties
%     end

    methods
        function obj = add_constraints(obj, mm, nm, dm, mpopt)
            %% find branches with flow limits
            dme = obj.data_model_element(dm);
            nme = obj.network_model_element(nm);
            ibr = find(dme.rate_a ~= 0 & dme.rate_a < 1e10);
            nl2 = length(ibr);      %% number of constrained branches
            mm.userdata.flow_constrained_branch_idx = ibr;

            if nl2
                %% port indexes
                nl = nme.nk;
                idx = [ibr; nl+ibr];

                %% limits
                flow_max = dme.rate_a(ibr); %% RATE_A

                %% branch flow constraints
                lim_type = upper(mpopt.opf.flow_lim(1));
                if lim_type == 'S'
                    fcn_flow = @(x)port_apparent_power_lim_fcn(nme, ...
                        mm.convert_x_m2n(x, nm), nm, idx, ...
                        [flow_max; flow_max] .^ 2);
                    hess_flow = @(x, lam)port_apparent_power_lim_hess(nme, ...
                        mm.convert_x_m2n(x, nm), lam, nm, idx);
                elseif lim_type == 'P'
                    fcn_flow = @(x)port_active_power_lim_fcn(nme, ...
                        mm.convert_x_m2n(x, nm), nm, idx, [flow_max; flow_max]);
                    hess_flow = @(x, lam)port_active_power_lim_hess(nme, ...
                        mm.convert_x_m2n(x, nm), lam, nm, idx);
                elseif lim_type == '2' || lim_type == 'P'
                    fcn_flow = @(x)port_active_power2_lim_fcn(nme, ...
                        mm.convert_x_m2n(x, nm), nm, idx, ...
                        [flow_max; flow_max] .^ 2);
                    hess_flow = @(x, lam)port_active_power2_lim_hess(nme, ...
                        mm.convert_x_m2n(x, nm), lam, nm, idx);
                elseif lim_type == 'I'
                    fcn_flow = @(x)port_current_lim_fcn(nme, ...
                        mm.convert_x_m2n(x, nm), nm, idx, ...
                        [flow_max; flow_max] .^ 2);
                    hess_flow = @(x, lam)port_current_lim_hess(nme, ...
                        mm.convert_x_m2n(x, nm), lam, nm, idx);
                else
                    error('mp.mme_branch_opf_ac/add_constraints: MPOPT.opf.flow_lim = ''%s'' not yet implemented.', mpopt.opf.flow_lim);
                end

                mm.add_nln_constraint({'Sf', 'St'}, [nl2;nl2], 0, fcn_flow, hess_flow);
            end
        end

        function obj = data_model_update(obj, mm, nm, dm, mpopt)
            dme = obj.data_model_element(dm);
            nme = obj.network_model_element(nm);

            %% branch active power flow
            pp = nm.get_idx('port');
            S_fr = nm.soln.gs_(pp.i1.branch(1):pp.iN.branch(1)) * dm.base_mva;
            S_to = nm.soln.gs_(pp.i1.branch(2):pp.iN.branch(2)) * dm.base_mva;

            %% shadow prices on branch flow constraints
            ibr = mm.userdata.flow_constrained_branch_idx;
            mu_flow_fr_ub = zeros(nme.nk, 1);
            mu_flow_to_ub = mu_flow_fr_ub;
            if length(ibr)
                lim_type = upper(mpopt.opf.flow_lim(1));
                nni = mm.get_idx('nli');
                lambda = mm.soln.lambda;
                if lim_type == 'P'
                    mu_flow_fr_ub(ibr) = lambda.ineqnonlin(nni.i1.Sf:nni.iN.Sf);
                    mu_flow_to_ub(ibr) = lambda.ineqnonlin(nni.i1.St:nni.iN.St);
                else
                    rate_a = dme.rate_a(ibr);
                    mu_flow_fr_ub(ibr) = 2 * lambda.ineqnonlin(nni.i1.Sf:nni.iN.Sf) .* rate_a;
                    mu_flow_to_ub(ibr) = 2 * lambda.ineqnonlin(nni.i1.St:nni.iN.St) .* rate_a;
                end
            end

            %% shadow prices on angle difference limits
            [mu_vad_lb, mu_vad_ub] = obj.ang_diff_prices(mm, nme);

            %% update in the data model
            dme.tab.pl_fr(dme.on) = real(S_fr);
            dme.tab.ql_fr(dme.on) = imag(S_fr);
            dme.tab.pl_to(dme.on) = real(S_to);
            dme.tab.ql_to(dme.on) = imag(S_to);
            dme.tab.mu_flow_fr_ub(dme.on) = mu_flow_fr_ub / dm.base_mva;
            dme.tab.mu_flow_to_ub(dme.on) = mu_flow_to_ub / dm.base_mva;
            dme.tab.mu_vad_lb(dme.on) = mu_vad_lb * pi/180;
            dme.tab.mu_vad_ub(dme.on) = mu_vad_ub * pi/180;
        end
    end     %% methods
end         %% classdef


function [msg, niter] = parallel_protocol(engine, evidence, msg)

bnet = bnet_from_engine(engine);
N = length(bnet.dag);
ns = bnet.node_sizes(:);

if ~isempty(engine.filename)
  fid = fopen(engine.filename, 'w');
  if fid == 0
    error(['could not open ' engine.filename ' for writing'])
  end
else
  fid = [];
end

converged = 0;
iter = 1;
hidden = find(isemptycell(evidence));
bel = cell(1,N);
old_bel = cell(1,N);
%nodes = mysetdiff(1:N, engine.disconnected_nodes);
nodes = find(~engine.disconnected_nodes_bitv);
while ~converged & (iter <= engine.max_iter)
  % Everybody updates their state in parallel
  for n=nodes(:)'
    cs_msg = children(engine.msg_dag, n);
    %msg{n}.lambda = compute_lambda(n, cs, msg);
    msg{n}.lambda = prod_lambda_msgs(n, cs_msg, msg, engine.msg_type);
    ps_orig = parents(bnet.dag, n);
    msg{n}.pi = CPD_to_pi(bnet.CPD{bnet.equiv_class(n)}, engine.msg_type, n, ps_orig, msg, evidence);
  end

  changed = 0;
  if ~isempty(fid)
    fprintf(fid, 'ITERATION %d\n', iter);
  end
  for n=hidden(:)' % this will not contain any disconnected nodes
    old_bel{n} = bel{n};
    bel{n}  = compute_bel(engine.msg_type, msg{n}.pi, msg{n}.lambda);
    if ~isempty(fid)
      fprintf(fid, 'node %d: %s\n', n, bel_to_str(bel{n}, engine.msg_type));
    end
    if engine.storebel
      engine.bel{n,iter} = bel{n};
    end
    if (iter == 1) | ~approxeq_bel(bel{n}, old_bel{n}, engine.tol, engine.msg_type)
      changed = 1;
    end
  end
  %converged = ~changed;
  converged = ~changed & (iter > 1);  % Sonia Leach changed this

  if ~converged
    % Everybody sends to all their neighbors in parallel
    for n=nodes(:)'
      % lambda msgs to parents
      ps_msg = parents(engine.msg_dag, n);
      ps_orig = parents(bnet.dag, n);
      for p=ps_msg(:)'
	j = engine.child_index{p}(n); % n is p's j'th child
	old_msg = msg{p}.lambda_from_child{j}(:);
	new_msg = CPD_to_lambda_msg(bnet.CPD{bnet.equiv_class(n)}, engine.msg_type, n, ps_orig, ...
				    msg, p, evidence);
	lam_msg = convex_combination_msg(old_msg, new_msg, engine.momentum, engine.msg_type);
	msg{p}.lambda_from_child{j} = lam_msg;
      end

      % pi msgs to children
      cs_msg = children(engine.msg_dag, n);
      for c=cs_msg(:)'
	j = engine.parent_index{c}(n); % n is c's j'th parent
	old_msg = msg{c}.pi_from_parent{j}(:);
	%new_msg = compute_pi_msg(n, cs, msg, c));
	new_msg = compute_bel(engine.msg_type, msg{n}.pi, prod_lambda_msgs(n, cs_msg, msg, engine.msg_type, c));
	pi_msg = convex_combination_msg(old_msg, new_msg, engine.momentum, engine.msg_type);
	msg{c}.pi_from_parent{j} = pi_msg;
      end
    end
    iter = iter + 1;
  end
end

if fid > 0, fclose(fid); end
%niter = iter - 1;
niter = iter;

%%%%%%%%%%

function str = bel_to_str(bel, type)

switch type
 case 'd', str = sprintf('%9.4f ', bel(:)');
 case 'g', str = sprintf('%9.4f ', bel.mu(:)');
end

%%%%%%%

function a = approxeq_bel(bel1, bel2, tol, type)

switch type
 case 'd', a = approxeq(bel1, bel2, tol);
 case 'g', a = approxeq(bel1.mu, bel2.mu, tol) & approxeq(bel1.Sigma, bel2.Sigma, tol);
end

%%%%%%%

function msg = convex_combination_msg(old_msg, new_msg, old_weight, type)

switch type
 case 'd', msg = old_weight * old_msg + (1-old_weight)*new_msg;
 case 'g', msg = new_msg;
end


function [wall_d, x_min, f_min] = pano_line_solver_6(lines, w_res, options)

    pk_loc = lines(1:2:end,1);

    % rotate
    line_label = lines(1:2:end,3);
    line_rot = find(line_label == 2);

    % initialize based on convex/concave
    if line_rot == 1

    else if line_rot == 2
            x_ini = [1.5; 0.5; -1; 2; 1; pk_loc; w_res];
        else if line_rot == 3
                x_ini = [0.5; 1.5; 1; 2; 2; pk_loc; w_res];
            else if line_rot == 4
                    x_ini = [0.25; 0.25; 0.5; 0.5; 1; pk_loc; w_res];
                else if line_rot == 5
                        x_ini = [0.75; 0.25; 1; 0.5; 0.5; pk_loc; w_res];
                        else if line_rot == 6
                            end
                    end
                end
            end
        end
    end

    x_min = Inf;
    f_min = Inf;
    % solve
    for t = 1:400
        %while 1
        f_old = Inf;
        for k = 1:5
            [x,f] = minFunc(@sampleEijOpt_6,x_ini,options);
            x_ini = x;
            % iterate until converge
            if abs(f- f_old) < 1e-5
                break
            end
            f_old = f;
        end
        %disp(f)
        if f < f_min
            f_min = f;
            x_min = x;
        end
        if f < 1e-5
            break
        end
        % TODO: fix initialization here
        rng('shuffle');
        if line_rot == 1
        else if line_rot == 2
                xo = rand(3,1);
                x_ini = [xo(1)+1;xo(2);-xo(3);2;1;pk_loc; w_res];
            else if line_rot == 3
                    xo = rand(2,1)*2;
                    x_ini = [xo(1);xo(2);xo(2)/2;2;2;pk_loc; w_res];
                else if line_rot == 4
                        xo = rand(2,1);
                        x_ini = [xo;(xo(2)+1)/2;(1+xo(1))/2;1;pk_loc; w_res];
                    else if line_rot == 5
                            xo = rand(2,1);
                            x_ini = [xo(1);xo(2);1;xo(1)/2;(1+xo(2))/2;pk_loc; w_res];
                        end
                    end
                end
            end
        end
    end
    disp(f_min)
    %keyboard

    % wall d
    cor = [0 0; 1,0; 1, x_min(3); x_min(4), x_min(3);x_min(4), x_min(5); 0, x_min(5)];
    wall_d = (cor - repmat([x_min(1) x_min(2)], 6, 1));
    wall_d = wall_d(:,1).^2 + wall_d(:,2).^2;
    wall_d = sqrt(wall_d);


function out=sign(x)

precision=x(1).precision;
out_rval=cell(size(x));
out_ival=cell(size(x));

for ii=1:numel(x)
 imag=false;
 [xrval,xival]=getVals(x,ii);

 out_rval{ii}=mpfr_absc(precision,xrval,xival);

 [out_rval{ii},out_ival{ii}]=mpfr_divc(precision,xrval,xival,out_rval{ii},mpExpForm('0',0));

end % for ii=1:max(ex,
out=class(struct('rval',out_rval,...
                  'ival',out_ival,...
                  'precision',precision),'mp');


function Show_RVT_Peak(R,fg),
   for (icol = 1:1:length(R)),
      figure(fg); clf
      set (fg, 'KeyPressFcn', @afni_fig_interface);
      subplot(211);
      plot (R(icol).t, real(R(icol).X),'g'); hold on
      if (~isempty(R(icol).RVT)),
         subplot (211);
            plot (R(icol).tmidprd,...
                  zscale(R(icol).RVT, max(R(icol).ptrace),...
                  min(R(icol).ptrace)), 'k');
      end
      plot( R(icol).tptrace, R(icol).ptrace,'ro',...
            R(icol).tptrace, R(icol).ptrace,'r');
      plot( R(icol).tntrace, R(icol).ntrace,'bo',...
            R(icol).tntrace, R(icol).ntrace,'b');
      plot (R(icol).tmidprd, R(icol).ptracemidprd,'kx');
      for (i=1:1:length(R(icol).prd)),
       text( R(icol).tmidprd(i), R(icol).ptracemidprd(i),...
             sprintf('%.2f', R(icol).prd(i)));
      end
      if (isfield(R(icol), 'tR')),
         if (isfield(R(icol), 'ptraceR')),
            plot( R(icol).tR, R(icol).ptraceR,'m');
            plot( R(icol).tR, R(icol).ntraceR,'y');
         end
         if (  isfield(R(icol), 'RVTRS')),
               plot( R(icol).tR,...
                     zscale(  R(icol).RVTRS, max(R(icol).ptrace),...
                              min(R(icol).ptrace) ),...
                     'k.');
         end
      end
      xlabel('time (sec)');
      title (R(icol).vname, 'Interpreter', 'None');

      subplot (413);
      vn = real(R(icol).X)./(abs(R(icol).X)+eps);
      plot (R(icol).t, vn, 'g'); hold on

      plot (R(icol).t, R(icol).phz./2./pi, 'm');
      if (isfield(R(icol), 'phzR')),
         plot (R(icol).tR, R(icol).phzR./2./pi, 'm-.');
      end
      xlabel('time (sec)');
      title ('Scaled by magnitude of analytical signal', 'Interpreter', 'None');
      legend({'Scaled signal','phase'});

      subplot (414);
      plot (R(icol).tst, R(icol).phz_slc(:,1), 'ro', ...
            R(icol).tst, R(icol).phz_slc(:,2), 'bo', ...
            R(icol).tst, R(icol).phz_slc(:,2), 'b-'); hold on;
      plot (R(icol).t, R(icol).phz, 'k');
      grid on
      xlabel('time (sec)');
      title ('Phase sampled at slice acquisition time');
      legend({'slice 0', 'slice 1', 'slice 1', 'original phase'});
      plotsign2(fg);
      drawnow;
   end
return;