text:
function [cfg, artifact] = ft_artifact_eog(cfg, data)

% FT_ARTIFACT_EOG scans data segments of interest for EOG artifacts.
%
% Use as
%   [cfg, artifact] = ft_artifact_eog(cfg)
% with the configuration options
%   cfg.dataset    = string with the filename
% or
%   cfg.headerfile = string with the filename
%   cfg.datafile   = string with the filename
% and optionally
%   cfg.headerformat
%   cfg.dataformat
%
% Alternatively you can use it as
%   [cfg, artifact] = ft_artifact_eog(cfg, data)
% where the input data is a structure as obtained from FT_PREPROCESSING.
%
% In both cases the configuration should also contain
%   cfg.trl        = structure that defines the data segments of interest, see FT_DEFINETRIAL
%   cfg.continuous = 'yes' or 'no' whether the file contains continuous data
%
% Prior to artifact detection, the data is preprocessed (again) with the following
% configuration parameters, which are optimal for identifying EOG artifacts.
%   cfg.artfctdef.eog.bpfilter   = 'yes'
%   cfg.artfctdef.eog.bpfilttype = 'but'
%   cfg.artfctdef.eog.bpfreq     = [1 15]
%   cfg.artfctdef.eog.bpfiltord  = 4
%   cfg.artfctdef.eog.hilbert    = 'yes'
%
% Artifacts are identified by means of thresholding the z-transformed value
% of the preprocessed data.
%   cfg.artfctdef.eog.channel      = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details
%   cfg.artfctdef.eog.cutoff       = z-value at which to threshold (default = 4)
%   cfg.artfctdef.eog.trlpadding   = number in seconds (default = 0.5)
%   cfg.artfctdef.eog.fltpadding   = number in seconds (default = 0.1)
%   cfg.artfctdef.eog.artpadding   = number in seconds (default = 0.1)
%
% The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of
% FT_DEFINETRIAL. The first column of which specifying the beginsamples of an
% artifact period, the second column contains the endsamples of the artifactperiods.
%
% To facilitate data-handling and distributed computing, you can use
%   cfg.inputfile   =  ...
% to read the input data from a *.mat file on disk. This mat files should contain
% only a single variable named 'data', corresponding to the input structure.
%
% See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG,
% FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE

% Copyright (C) 2003-2011, Jan-Mathijs Schoffelen & Robert Oostenveld
%
% 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$

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init

% ft_preamble provenance is not needed because just a call to ft_artifact_zvalue
% ft_preamble loadvar data is not needed because ft_artifact_zvalue will do this

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed',    {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});
cfg = ft_checkconfig(cfg, 'forbidden',  {'padding', 'pretim', 'psttim'});

% set default rejection parameters
cfg.artfctdef            = ft_getopt(cfg,               'artfctdef', []);
cfg.artfctdef.eog        = ft_getopt(cfg.artfctdef,     'eog',       []);
cfg.artfctdef.eog.method = ft_getopt(cfg.artfctdef.eog, 'method',    'zvalue');

if isfield(cfg.artfctdef.eog, 'artifact')
  fprintf('eog artifact detection has already been done, retaining artifacts\n');
  artifact = cfg.artfctdef.eog.artifact;
  return
end

if ~strcmp(cfg.artfctdef.eog.method, 'zvalue')
  ft_error('EOG artifact detection only works with method=''zvalue''');
end

% for backward compatibility
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'sgn',     'channel'});
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'passbnd', 'bpfreq'});
cfg.artfctdef.eog = ft_checkconfig(cfg.artfctdef.eog, 'renamed', {'padding', 'trlpadding'});

% settings for preprocessing
cfg.artfctdef.eog.bpfilter    = ft_getopt(cfg.artfctdef.eog, 'bpfilter',   'yes');
cfg.artfctdef.eog.bpfreq      = ft_getopt(cfg.artfctdef.eog, 'bpfreq',     [1 15]);
cfg.artfctdef.eog.bpfiltord   = ft_getopt(cfg.artfctdef.eog, 'bpfiltord',   4);
cfg.artfctdef.eog.bpfilttype  = ft_getopt(cfg.artfctdef.eog, 'bpfilttype', 'but');
cfg.artfctdef.eog.hilbert     = ft_getopt(cfg.artfctdef.eog, 'hilbert',    'yes');

% settings for the zvalue subfunction
cfg.artfctdef.eog.channel    = ft_getopt(cfg.artfctdef.eog, 'channel',    'EOG');
cfg.artfctdef.eog.cutoff     = ft_getopt(cfg.artfctdef.eog, 'cutoff',     4);
cfg.artfctdef.eog.trlpadding = ft_getopt(cfg.artfctdef.eog, 'trlpadding', 0.5);
cfg.artfctdef.eog.fltpadding = ft_getopt(cfg.artfctdef.eog, 'fltpadding', 0.1);
cfg.artfctdef.eog.artpadding = ft_getopt(cfg.artfctdef.eog, 'artpadding', 0.1);

% construct a temporary configuration that can be passed onto FT_ARTIFACT_ZVALUE
tmpcfg                  = cfg;
tmpcfg.artfctdef.zvalue = cfg.artfctdef.eog;
tmpcfg.artfctdef        = rmfield(tmpcfg.artfctdef, 'eog');

% call the zvalue artifact detection function, where the data is either passed
% into the function by the user or read from file with cfg.inputfile
hasdata = exist('data', 'var');
if ~hasdata
  tmpcfg             = ft_checkconfig(tmpcfg, 'dataset2files', 'yes');
  tmpcfg             = ft_checkconfig(tmpcfg, 'required', {'headerfile', 'datafile'});
  [tmpcfg, artifact] = ft_artifact_zvalue(tmpcfg);
else
  tmpcfg.artfctdef.zvalue.trlpadding = 0;
  tmpcfg.artfctdef.zvalue.fltpadding = 0;
  ft_warning('trlpadding and fltpadding are set to zero to avoid filter problems with NaN, see bug3193 for details');
  [tmpcfg, artifact] = ft_artifact_zvalue(tmpcfg, data);
end
cfg.artfctdef.eog  = tmpcfg.artfctdef.zvalue;


text:
function ffmsh_2d_size_print ( title, v_num, e_num, t_num )

%*****************************************************************************80
%
%% FFMSH_2D_SIZE_PRINT prints the sizes of an FFMSH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 December 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string TITLE, a title.
%
%    Input, integer V_NUM, the number of vertices.
%
%    Input, integer E_NUM, the number of boundary edges.
%
%    Input, integer T_NUM, the number of triangles.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of vertices = %d\n', v_num );
  fprintf ( 1, '  Number of boundary edges = %d\n', e_num );
  fprintf ( 1, '  Number of triangles = %d\n', t_num );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function origin = dtiMrMeshOrigin(handles)
% Computes the (x,y,z) origin of the image plane data
%
%   origin = dtiMrMeshOrigin(handles)
%
% NOTE: This routine was extracted from dtiMrMesh3AxisImage so we could
% build independent mrMesh outputs.  I think it may be computing the origin
% of the quarter images from dtiSplit... routine.
%
% Authors: Wandell, Dougherty
%
% Stanford VISTA Team

curPosition = dtiGet(handles,'curpos');

[xImX,xImY,xImZ] = dtiMrMeshImageCoords(handles,1,curPosition(1));
[yImX,yImY,yImZ] = dtiMrMeshImageCoords(handles,2,curPosition(2));
[zImX,zImY,zImZ] = dtiMrMeshImageCoords(handles,3,curPosition(3));

% For x,y,z you place the current position into the relevant location and
% then for the other two you find the value that is zero (which is the
% mid-point of the coordinates and substract off half of the number
% coordinates. I don't understand why (BW).
origin.x = -[-curPosition(1), ...
        find(xImY(:,1)==0) - length(xImY(:,1))/2, ...
        find(xImZ(1,:)==0) - length(xImZ(1,:))/2];

origin.y = -[find(yImX(:,1)==0) - length(yImX(:,1))/2, ...
        -curPosition(2), ...
        find(yImZ(1,:)==0) - length(yImZ(1,:))/2];

origin.z = -[find(zImX(1,:)==0) - length(zImX(1,:))/2, ...
        find(zImY(:,1)==0) - length(zImY(:,1))/2, ...
        -curPosition(3)];

return;

%------------------------------------
function [x,y,z] = dtiMrMeshImageCoords(handles,sliceThisDim,sliceNum)
%
%   [x,y,z] = dtiMrMeshImageCoords(handles,sliceThisDim,sliceNum);
%
% Produces an array of grid points that can be transformed in dtiGetSlice
% to image coords.  They are used for interpolating values in dtGetSlice.
%
% This routine should be extracted and then called from dtGetSlice  instead
% of the code that is there.
%
% Stanford VISTA Team

imDims = dtiGet(1, 'defaultBoundingBox');

nvals = max(imDims) - min(imDims) + 1;

% Computes a single integer for the desired slice, and two vectors showing
% the support of the other two.  So, if you are in the x-slice, you get
% that number of the x-slide and two vectors showing the y and z
% coordinates.
if(sliceThisDim == 1), x = sliceNum;
else x = linspace(imDims(1,1),imDims(2,1),nvals(1));
end;

if(sliceThisDim == 2), y = sliceNum;
else y = linspace(imDims(1,2),imDims(2,2),nvals(2));
end;

if(sliceThisDim == 3), z = sliceNum;
else z = linspace(imDims(1,3),imDims(2,3),nvals(3));
end;

% Convert the single number and the two linear dimensions into 3 3D
% matrices that define the x,y,z coordinates at each anatomical point.
% The singleton dimension is all one value, and the other two 3D
% matrices combine
[x,y,z] = meshgrid(x,y,z);

% Squeeze out the singleton dimension.
x = squeeze(x);
y = squeeze(y);
z = squeeze(z);

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function choices = simplex_grid(dim, discretization, include_edges)
%SIMPLEX_GRID returns a discrete set of points from a simplex
%
% points = simplex_grid(dim, discretization[, include_edges=false]);
%
% Inputs:
%                 dim 1x1 dimensionality D
%      discretization 1x1 Number of discrete points along each axis.
%       include_edges 1x1 If true, allow components to be exactly zero or one.
%                         As this often causes problems, the default is false.
%
% Outputs:
%            choices  LOTS x D, It should be that all(1 == sum(choices, 2)).

% Iain Murray, January 2009

% If dim==1, the only point that is allowed is [1], and that disagrees with the
% include_edges default. For now, just don't allow this silly case.
assert(dim > 1);

vec = @(x) x(:);

if ~exist('include_edges', 'var')
    include_edges = false;
end

if include_edges
    ww = 1/(discretization-1);
    tics = (0:ww:1)';
else
    ww = 1/(discretization+1);
    tics = (ww:ww:(1-ww))';
end

choices = tics;
cur_sum = choices;

% Build up choices one component at a time
for d = 2:(dim-1)
    % For each existing choice, consider setting next component to every choice
    % in tics
    prev_length = size(choices, 1);
    proposed_next = vec(repmat(tics', prev_length, 1));
    proposed_sum = proposed_next + repmat(cur_sum, discretization, 1);
    proposed_choices = [proposed_next, repmat(choices, discretization, 1)];
    % Only keep proposals that can lead to valid points on simplex
    idx = proposed_sum <= (1 - tics(1)*(dim-d));
    choices = proposed_choices(idx, :);
    cur_sum = proposed_sum(idx);
end

% Final component must be chosen to make choices normalized
choices = [choices, 1-cur_sum];

author: jacobeisenstein

repo: SAGE


text:
function y = vl_nnspnorm(x, param, dzdy)
%VL_NNSPNORM CNN spatial normalization.
%   Y = VL_NNSPNORM(X, PARAM) computes the spatial normalization of
%   the data X with parameters PARAM = [PH PW ALPHA BETA]. Here PH and
%   PW define the size of the spatial neighbourhood used for
%   nomalization.
%
%   For each feature channel, the function computes the sum of squares
%   of X inside each rectangle, N2(i,j). It then divides each element
%   of X as follows:
%
%      Y(i,j) = X(i,j) / (1 + ALPHA * N2(i,j))^BETA.
%
%   DZDX = VL_NNSPNORM(X, PARAM, DZDY) computes the derivative of the
%   block projected onto DZDY. DZDX and DZDY have the same dimensions
%   as X and Y respectively.

% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

pad = floor((param(1:2)-1)/2) ;
pad = [pad ; param(1:2)-1-pad] ;

n2 = vl_nnpool(x.*x, param(1:2), 'method', 'avg', 'pad', pad) ;
f = 1 + param(3) * n2 ;

if nargin <= 2 || isempty(dzdy)
  y = f.^(-param(4)) .* x ;
else
  t = vl_nnpool(x.*x, param(1:2), f.^(-param(4)-1) .* dzdy .* x, 'method', 'avg', 'pad', pad) ;
  y = f.^(-param(4)) .* dzdy - 2 * param(3)*param(4) * x .* t ;
end

author: willard-yuan

repo: cnn-for-image-retrieval


text:
function [ x, w ] = fejer1_rule_compute ( n )

%*****************************************************************************80
%
%% FEJER1_RULE_COMPUTE computes a Fejer Type 1 rule.
%
%  Modified:
%
%    06 March 2007
%
%  Author:
%
%    Joerg Waldvogel
%
%  Reference:
%
%    Joerg Waldvogel,
%    Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules,
%    BIT Numerical Mathematics
%    Volume 43, Number 1, pages 1-18, 2003.
%
%  Parameters:
%
%    Input, integer N, the order of the rule.
%
%    Output, real X(N), W(N), the abscissas and weights of the rule.
%
  N = [ 1 : 2 : n-1 ]';
  L = length ( N );
  m = n - L;
  K = [ 0 : m-1 ]';

  s = zeros ( L+1, 1 );
  v0 = [ 2 * exp(i*pi*K/n) ./ ( 1 - 4 * K.^2 ); s ];

  v1 = v0(1:end-1) + conj ( v0(end:-1:2) );
  w = ifft ( v1 );

  x = cos ( pi * ( (n:-1:1)' - 1 / 2 ) / n );

  return
end


text:
%% IMPORTSWARMDB
function obj = importswarmdb(obj, dbname, auth, snum, enum)
    % IMPORTSWARMDB
    % Load a swarm database metrics table into an EventRate object
    % eventrate = importswarmdb(erobj, dbname, auth, snum, enum);
    %
    % INPUT:
    %	dbname		the path of the database (must have a 'metrics' table)
    %	auth		name of the grid to load swarm tracking metrics for
    %	snum,enum	start and end datenumbers (Matlab time format, see 'help datenum')
    %
    % OUTPUT:
    %	obj		an eventrate object
    %
    % Example:
    %	erobj = importswarmdb('/avort/devrun/dbswarm/swarm_metadata', 'RD_lo', datenum(2010, 7, 1), datenum(2010, 7, 14) );

    % Glenn Thompson, 20100714

    % initialize
    obj.dbroot = dbname;
    obj.snum = snum;
    obj.enum = enum;
    obj.auth = auth;

    % check that database exists
    dbtablename = sprintf('%s.metrics',dbname);
    if exist(dbtablename,'file')
        % load the data
        try
            db = dbopen(dbname, 'r');
        catch me
            fprintf('Error: Could not open %s for reading',dbname);
                return;
        end
        db = dblookup_table(db, 'metrics');
        if (dbquery(db, 'dbRECORD_COUNT')==0)
            fprintf('Error: Could not open %s for reading',dbtablename);
            return;
        end
        db = dbsubset(db, sprintf('auth ~= /.*%s.*/',auth));
        numrows = dbquery(db,'dbRECORD_COUNT');
        debug.print_debug(sprintf('Got %d rows after auth subset',numrows),2);
        sepoch = datenum2epoch(snum);
        eepoch = datenum2epoch(enum);
        db = dbsubset(db, sprintf('timewindow_starttime >= %f && timewindow_endtime <= %f',sepoch,eepoch));
        numrows = dbquery(db,'dbRECORD_COUNT');
        debug.print_debug(sprintf('Got %d rows after time subset',numrows),2);

        if numrows > 0
            % Note that metrics are only saved when mean_rate >= 1.
            % Therefore there will be lots of mean_rate==0 timewindows not in
            % database.
            [tempsepoch, tempeepoch, mean_rate, median_rate, mean_mag, cum_mag] = dbgetv(db,'timewindow_starttime', 'timewindow_endtime', 'mean_rate', 'median_rate', 'mean_ml', 'cum_ml');
            obj.binsize = (tempeepoch(1) - tempsepoch(1))/86400;
            obj.stepsize = min(tempsepoch(2:end) - tempsepoch(1:end-1))/86400;
            obj.time = snum+obj.stepsize:obj.stepsize:enum;
            obj.numbins = length(obj.time);
            obj.mean_rate = zeros(obj.numbins, 1);
            obj.counts = zeros(obj.numbins, 1);
            obj.median_rate = zeros(obj.numbins, 1);
            obj.mean_mag = zeros(obj.numbins, 1);
            obj.cum_mag = zeros(obj.numbins, 1);
            for c=1:length(tempeepoch)
                tempenum = epoch2datenum(tempeepoch(c));
                i = find(obj.time == tempenum);
                obj.mean_rate(i) = mean_rate(c);
                obj.counts(i) = mean_rate(c) * (obj.binsize * 24);
                obj.median_rate(i) = median_rate(c);
                obj.mean_mag(i) = mean_mag(c);
                obj.cum_mag(i) = cum_mag(c);
            end
        end
        dbclose(db);

    else
        % error - table does not exist
        fprintf('Error: %s does not exist',dbtablename);
        return;
    end

    obj.total_counts = sum(obj.counts)*obj.stepsize/obj.binsize;

end

author: geoscience-community-codes

repo: GISMO


text:
% This software comes free with the hope that it is useful, but without any
% warranty.
% It is published under the terms of the GNU General Public
% License v3.0. You are free to use, modify and redistribute the code,
% provided the original source is attributed and further distribution is
% made under the same license.
%
%% Copyright (c) Florian Denk, 2018
% Email: florian.denk@uni-oldenburg.de
% Department of Medical Physics and Acoustics, University of Oldenburg
%%

function vf_sig = fftR(v_sig,N)
% vf_sig = fftR(v_sig, N)
% input: v_sig: input signal to be transformed, column vector or Matrix
%        N    : length of fft
% Function that does FFT for real signals and truncates spectrum to half
% sanpling frequency. Otherwise same behaviour as matlab's fft function.
% Input can be vector or matrix, for matrix fft will be performed
% column-wise.
%
% Florian Denk, March 2016

if nargin < 2
    N = size(v_sig,1);
end
if ~isreal(v_sig)
    warning('This function should only be applied to real-valued signals')
end

% do FFT
vf_sig = fft(v_sig,N);

% truncate spectrum
vf_sig = vf_sig( 1 : ceil(end/2)+1,:,:,:);

end

author: m-r-s

repo: hearingaid-prototype


text:
% Test file for @chebfun/waterfall.m.

function pass = test_waterfall(pref)

if ( nargin < 1 )
    pref = chebfunpref();
end

hfig = figure('Visible', 'off');

Q = chebfun(@(x) [sin(pi*x) sin(pi*(x - 0.3)) sin(pi*(x - 0.6))], pref);
pass(1) = doesNotCrash(@() waterfall(Q));
pass(2) = doesNotCrash(@() waterfall(chebfun(@(x) 0*x)));
pass(3) = doesNotCrash(@() waterfall(Q.'));
pass(4) = doesNotCrash(@() waterfall(Q, [0 0.3 0.6]));
pass(5) = doesNotCrash(@() waterfall(cheb2quasi(Q)));
pass(6) = doesNotCrash(@() waterfall(Q, 'LineWidth', 2, 'FaceAlpha', 0.5, ...
    'FaceColor', 'r'));

close(hfig);

end

function pass = doesNotCrash(fn)

try
    fn();
    pass = true;
catch ME;
    pass = false;
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun