plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
sophont01/fStackIID-master
|
RollingGuidanceFilter.m
|
.m
|
fStackIID-master/libs/RGF/RollingGuidanceFilter.m
| 2,182 |
utf_8
|
5f422c600926de19f465b4d417053d00
|
%
% Rolling Guidance Filter
%
% res = RollingGuidanceFilter(I,sigma_s,sigma_r,iteration) filters image
% "I" by removing its small structures. The borderline between "small"
% and "large" is determined by the parameter sigma_s. The sigma_r is
% fixed to 0.1. The filter is an iteration process. "iteration" is used
% to control the number of iterations.
%
% Paras:
% @I : input image, DOUBLE image, any # of channels
% @sigma_s : spatial sigma (default 3.0). Controlling the spatial
% weight of bilateral filter and also the filtering scale of
% rolling guidance filter.
% @sigma_r : range sigma (default 0.1). Controlling the range weight of
% bilateral filter.
% @iteration : the iteration number of rolling guidance (default 4).
%
%
% Example
% ==========
% I = im2double(imread('image.png'));
% res = RollingGuidanceFilter(I,3,0.05,4);
% figure, imshow(res);
%
%
% Note
% ==========
% This implementation filters multi-channel/color image by separating its
% channels, so the result of this implementation will be different with
% that in the corresponding paper. To generate the results in the paper,
% please refer to our executable file or C++ implementation on our
% website.
%
% ==========
% The Code is created based on the method described in the following paper:
% [1] "Rolling Guidance Filter", Qi Zhang, Li Xu, Jiaya Jia, European
% Conference on Computer Vision (ECCV), 2014
%
% The code and the algorithm are for non-comercial use only.
%
%
% Author: Qi Zhang ([email protected])
% Date : 08/14/2014
% Version : 1.0
% Copyright 2014, The Chinese University of Hong Kong.
%
function res = RollingGuidanceFilter(I,sigma_s,sigma_r,iteration)
if ~exist('iteration','var')
iteration = 4;
end
if ~exist('sigma_s','var')
sigma_s = 3;
end
if ~exist('sigma_r','var')
sigma_r = 0.1;
end
res = I.*0;
for i=1:iteration
disp(['RGF iteration ' num2str(i) '...']);
for c=1:size(I,3)
G = res(:,:,c);
res(:,:,c) = bilateralFilter(I(:,:,c),G,min(G(:)),max(G(:)),sigma_s,sigma_r);
end
end
end
|
github
|
sophont01/fStackIID-master
|
bilateralFilter.m
|
.m
|
fStackIID-master/libs/RGF/bilateralFilter.m
| 6,813 |
utf_8
|
2d0dd83ba74af5b1ab0dd2a2d7632295
|
%
% output = bilateralFilter( data, edge, ...
% edgeMin, edgeMax, ...
% sigmaSpatial, sigmaRange, ...
% samplingSpatial, samplingRange )
%
% Bilateral and Cross-Bilateral Filter using the Bilateral Grid.
%
% Bilaterally filters the image 'data' using the edges in the image 'edge'.
% If 'data' == 'edge', then it the standard bilateral filter.
% Otherwise, it is the 'cross' or 'joint' bilateral filter.
% For convenience, you can also pass in [] for 'edge' for the normal
% bilateral filter.
%
% Note that for the cross bilateral filter, data does not need to be
% defined everywhere. Undefined values can be set to 'NaN'. However, edge
% *does* need to be defined everywhere.
%
% data and edge should be of the greyscale, double-precision floating point
% matrices of the same size (i.e. they should be [ height x width ])
%
% data is the only required argument
%
% edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data'
% for the normal bilateral filter) and is useful when the input is in a
% range that's not between 0 and 1. For instance, if you are filtering the
% L channel of an image that ranges between 0 and 100, set edgeMin to 0 and
% edgeMax to 100.
%
% edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge( : ) ).
% This is probably *not* what you want, since the input may not span the
% entire range.
%
% sigmaSpatial and sigmaRange specifies the standard deviation of the space
% and range gaussians, respectively.
% sigmaSpatial defaults to min( width, height ) / 16
% sigmaRange defaults to ( edgeMax - edgeMin ) / 10.
%
% samplingSpatial and samplingRange specifies the amount of downsampling
% used for the approximation. Higher values use less memory but are also
% less accurate. The default and recommended values are:
%
% samplingSpatial = sigmaSpatial
% samplingRange = sigmaRange
%
function output = bilateralFilter( data, edge, edgeMin, edgeMax, sigmaSpatial, sigmaRange, ...
samplingSpatial, samplingRange )
if( ndims( data ) > 2 ),
error( 'data must be a greyscale image with size [ height, width ]' );
end
if( ~isa( data, 'double' ) ),
error( 'data must be of class "double"' );
end
if ~exist( 'edge', 'var' ),
edge = data;
elseif isempty( edge ),
edge = data;
end
if( ndims( edge ) > 2 ),
error( 'edge must be a greyscale image with size [ height, width ]' );
end
if( ~isa( edge, 'double' ) ),
error( 'edge must be of class "double"' );
end
inputHeight = size( data, 1 );
inputWidth = size( data, 2 );
if ~exist( 'edgeMin', 'var' ),
edgeMin = min( edge( : ) );
warning( 'edgeMin not set! Defaulting to: %f\n', edgeMin );
end
if ~exist( 'edgeMax', 'var' ),
edgeMax = max( edge( : ) );
warning( 'edgeMax not set! Defaulting to: %f\n', edgeMax );
end
edgeDelta = edgeMax - edgeMin;
if ~exist( 'sigmaSpatial', 'var' ),
sigmaSpatial = min( inputWidth, inputHeight ) / 16;
fprintf( 'Using default sigmaSpatial of: %f\n', sigmaSpatial );
end
if ~exist( 'sigmaRange', 'var' ),
sigmaRange = 0.1 * edgeDelta;
fprintf( 'Using default sigmaRange of: %f\n', sigmaRange );
end
if ~exist( 'samplingSpatial', 'var' ),
samplingSpatial = sigmaSpatial;
end
if ~exist( 'samplingRange', 'var' ),
samplingRange = sigmaRange;
end
if size( data ) ~= size( edge ),
error( 'data and edge must be of the same size' );
end
% parameters
derivedSigmaSpatial = sigmaSpatial / samplingSpatial;
derivedSigmaRange = sigmaRange / samplingRange;
paddingXY = floor( 2 * derivedSigmaSpatial ) + 1;
paddingZ = floor( 2 * derivedSigmaRange ) + 1;
% allocate 3D grid
downsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ;
gridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
gridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
% compute downsampled indices
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );
% ii =
% 0 0 0 0 0
% 1 1 1 1 1
% 2 2 2 2 2
% jj =
% 0 1 2 3 4
% 0 1 2 3 4
% 0 1 2 3 4
% so when iterating over ii( k ), jj( k )
% get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first)
di = round( ii / samplingSpatial ) + paddingXY + 1;
dj = round( jj / samplingSpatial ) + paddingXY + 1;
dz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1;
% perform scatter (there's probably a faster way than this)
% normally would do downsampledWeights( di, dj, dk ) = 1, but we have to
% perform a summation to do box downsampling
for k = 1 : numel( dz ),
dataZ = data( k ); % traverses the image column wise, same as di( k )
if ~isnan( dataZ ),
dik = di( k );
djk = dj( k );
dzk = dz( k );
gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ;
gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1;
end
end
% make gaussian kernel
kernelWidth = 2 * derivedSigmaSpatial + 1;
kernelHeight = kernelWidth;
kernelDepth = 2 * derivedSigmaRange + 1;
halfKernelWidth = floor( kernelWidth / 2 );
halfKernelHeight = floor( kernelHeight / 2 );
halfKernelDepth = floor( kernelDepth / 2 );
[gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1, 0 : kernelHeight - 1, 0 : kernelDepth - 1 );
gridX = gridX - halfKernelWidth;
gridY = gridY - halfKernelHeight;
gridZ = gridZ - halfKernelDepth;
gridRSquared = ( gridX .* gridX + gridY .* gridY ) / ( derivedSigmaSpatial * derivedSigmaSpatial ) + ( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange );
kernel = exp( -0.5 * gridRSquared );
% convolve
blurredGridData = convn( gridData, kernel, 'same' );
blurredGridWeights = convn( gridWeights, kernel, 'same' );
% divide
blurredGridWeights( blurredGridWeights == 0 ) = -2; % avoid divide by 0, won't read there anyway
normalizedBlurredGrid = blurredGridData ./ blurredGridWeights;
normalizedBlurredGrid( blurredGridWeights < -1 ) = 0; % put 0s where it's undefined
% for debugging
% blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back
% upsample
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); % meshgrid does x, then y, so output arguments need to be reversed
% no rounding
di = ( ii / samplingSpatial ) + paddingXY + 1;
dj = ( jj / samplingSpatial ) + paddingXY + 1;
dz = ( edge - edgeMin ) / samplingRange + paddingZ + 1;
% interpn takes rows, then cols, etc
% i.e. size(v,1), then size(v,2), ...
output = interpn( normalizedBlurredGrid, di, dj, dz );
a = interpn(blurredGridWeights,di,dj,dz);
% correction for outliers (January 10, 2013, Qiong Yan)
mask = isnan(output);
output(mask) = data(mask);
|
github
|
sophont01/fStackIID-master
|
recursivepartition.m
|
.m
|
fStackIID-master/libs/GRWfusion/recursivepartition.m
| 6,561 |
utf_8
|
4256fefd5a912098ab9223e2ce5207ea
|
function segAnswer=recursivepartition(W,stop,algFlag,volFlag,points)
%Function segAnswer=recursivepartition(W,stop,algFlag,volFlag,points)
%recursively calls partitiongraph.m until the stop criteria is statisfied.
%Function outputs a vector containing an integer label for every node
%corresponding to the unsupervised partitions.
%
%Inputs: W - Adjacency matrix (weighted) for a graph
% stop - The recursion stop criterion
% algFlag - Flag specifying the segmentation algorithm to use
% 0: Isoperimetric (Default)
% 1: Spectral
% volFlag - Flag specifying which notion of volume to use
% 0: Degree i.e. vol = sum(degree_of_neighbors) (Default)
% 1: Uniform i.e. vol = 1
% points - Optional parameter giving the coordinates of the
% total point set (puts function into diagnostic mode)
%
%Outputs: answer - A vector containing an integer label of every node
% indicating its group
%
%
%5/23/03 - Leo Grady
% Copyright (C) 2002, 2003 Leo Grady <[email protected]>
% Computer Vision and Computational Neuroscience Lab
% Department of Cognitive and Neural Systems
% Boston University
% Boston, MA 02215
%
% 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 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
%
% Date - $Id: recursivepartition.m,v 1.3 2003/08/21 17:29:29 lgrady Exp $
%========================================================================%
%Read inputs
if nargin < 3
[algFlag,volFlag]=deal(0);
end
if nargin < 4
volFlag=0;
end
%Initialization
N=length(W);
%Determine diagnostic mode and partition
if nargin == 5
segAnswer=performrecursion(W,stop,algFlag,volFlag,zeros(N,1), ...
[1:N]',1,points,1:N);
else
segAnswer=performrecursion(W,stop,algFlag,volFlag,zeros(N,1), ...
[1:N]',1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function answer=performrecursion(W,stop,algFlag,volFlag, ...
answer,index,recursionDepth,points,currPoints)
%Function answer=performrecursion(W,stop,algFlag,volFlag, ...
% answer,index,recursionDepth,points,currPoints) actually performs the
% recursion.
%
%Inputs: W - Adjacency matrix (weighted) for a graph
% stop - The recursion stop criterion
% algFlag - Flag specifying the segmentation algorithm to use
% 0: Isoperimetric (Default)
% 1: Spectral
% volFlag - Flag specifying which notion of volume to use
% 0: Degree i.e. vol = sum(degree_of_neighbors) (Default)
% 1: Uniform i.e. vol = 1
% answer - The current answer vector (start with all zeros)
% index - Index of current point set in the answer vector
% recursionDepth - Current recursion depth
% points - Optional parameter giving the Nx2 coordinates of the
% total point set (puts function into diagnostic mode)
% currPoints - Optional parameter (necessary if points are used)
% that gives a list of the current points under
% consideration
%
%Outputs: answer - A vector containing an integer label of every node
% indicating its group
%
%5/23/03 - Leo Grady
%Initialization
N=length(W);
CUTOFF=5; %Number of nodes below which a new partition is not attempted
RECURSIONCAP=90;
%Partition current graph
if N > CUTOFF
[part1,part2,constant,xFunction]=partitiongraph(W,algFlag,volFlag);
else
constant=2;
end
%Check for diagnostic mode
if nargin > 7
%%Diagnostic mode
%Output sizes of partition and their constant
constant
sizePart1=size(part1)
sizePart2=size(part2)
%Output partition to figure
figure
plot(points(:,1),points(:,2),'k.','MarkerSize',24);
hold on
plot(points(currPoints(part1),1),max(points(:,2))- ...
points(currPoints(part1),2),'r.','MarkerSize',24);
plot(points(currPoints(part2),1),max(points(:,2))- ...
points(currPoints(part2),2),'b.','MarkerSize',24);
title(sprintf('Constant: %d',full(constant)))
axis equal
axis tight
axis off
hold off
tilefigs
%If partition is of high enough quality, continue recursion
if (constant < stop) & (recursionDepth < RECURSIONCAP)
%Accept partition and update answer vector
tmpInd=find(answer>answer(index(1)));
answer(tmpInd)=answer(tmpInd)+1; %Make room for new class
answer(index(part2))=answer(index(part2))+1; %Mark new class
%Continue recursion on each partition
if size(part1,1) > CUTOFF
answer=performrecursion(W(part1,part1),stop,algFlag, ...
volFlag,answer,index(part1),recursionDepth+1,points, ...
currPoints(part1));
end
if size(part2,2) > CUTOFF
answer=performrecursion(W(part2,part2),stop,algFlag, ...
volFlag,answer,index(part2),recursionDepth+1,points, ...
currPoints(part2));
end
else
answer=answer;
end
else
%%Standard (non-diagnostic) mode
%If partition is of high enough quality, continue recursion
if (constant < stop) & (recursionDepth < RECURSIONCAP)
%Accept partition and update answer vector
tmpInd=find(answer>answer(index(1)));
answer(tmpInd)=answer(tmpInd)+1; %Make room for new class
answer(index(part2))=answer(index(part2))+1; %Mark new class
%Continue recursion on each partition
if size(part1,1) > CUTOFF
answer=performrecursion(W(part1,part1),stop,algFlag, ...
volFlag,answer,index(part1),recursionDepth+1);
end
if size(part2,2) > CUTOFF
answer=performrecursion(W(part2,part2),stop,algFlag, ...
volFlag,answer,index(part2),recursionDepth+1);
end
else
answer=answer;
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
InitializeWiMaxLDPC.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/cml/mat/InitializeWiMaxLDPC.m
| 7,281 |
utf_8
|
85886f83df253368a709769854748fd1
|
% File: InitializeWiMaxLDPC.m
%
% Description: Initializes the WiMax LDPC encoder/decoder
%
% The calling syntax is:
% [H_rows, H_cols, P] = InitializeWiMaxLDPC( rate, size, ind )
%
% Where:
% H_rows = a M-row matrix containing the indices of the non-zero rows of H excluding the dual-diagonal portion of H.
% H_cols = a (N-M)+z-row matrix containing the indices of the non-zeros rows of H.
% P = a z times z matrix used in encoding
%
% rate = the code rate
% size = the size of the code (number of code bits):
% = 576:96:2304
% ind = Selects either code 'A' or 'B' for rates 2/3 and 3/4
% = 0 for code rate type 'A'
% = 1 for code rate type 'B'
% = [empty array] for all other code rates
%
% Copyright (C) 2007-2008, Rohit Iyer Seshadri and Matthew C. Valenti
%
% Last updated on June. 23, 2007.
%
% Function InitializeWiMaxLDPC is part of the Iterative Solutions
% Coded Modulation Library. The Iterative Solutions Coded Modulation
% Library is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published
% by the Free Software Foundation; either version 2.1 of the License,
% or (at your option) any later version.
%
% This library 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
% Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with this library; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
function [H_rows, H_cols,P]= InitializeWiMaxLDPC(rate, nldpc, ind)
epsilon=1e-3;
rt_flag=0;
if (abs(rate-1/2) <epsilon )
rt_flag=1;
Hbm=[-1 94 73 -1 -1 -1 -1 -1 55 83 -1 -1 7 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1;...
-1 27 -1 -1 -1 22 79 9 -1 -1 -1 12 -1 0 0 -1 -1 -1 -1 -1 -1 -1 -1 -1;...
-1 -1 -1 24 22 81 -1 33 -1 -1 -1 0 -1 -1 0 0 -1 -1 -1 -1 -1 -1 -1 -1;...
61 -1 47 -1 -1 -1 -1 -1 65 25 -1 -1 -1 -1 -1 0 0 -1 -1 -1 -1 -1 -1 -1;...
-1 -1 39 -1 -1 -1 84 -1 -1 41 72 -1 -1 -1 -1 -1 0 0 -1 -1 -1 -1 -1 -1;...
-1 -1 -1 -1 46 40 -1 82 -1 -1 -1 79 0 -1 -1 -1 -1 0 0 -1 -1 -1 -1 -1;...
-1 -1 95 53 -1 -1 -1 -1 -1 14 18 -1 -1 -1 -1 -1 -1 -1 0 0 -1 -1 -1 -1;...
-1 11 73 -1 -1 -1 2 -1 -1 47 -1 -1 -1 -1 -1 -1 -1 -1 -1 0 0 -1 -1 -1;...
12 -1 -1 -1 83 24 -1 43 -1 -1 -1 51 -1 -1 -1 -1 -1 -1 -1 -1 0 0 -1 -1;...
-1 -1 -1 -1 -1 94 -1 59 -1 -1 70 72 -1 -1 -1 -1 -1 -1 -1 -1 -1 0 0 -1;...
-1 -1 7 65 -1 -1 -1 -1 39 49 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 0 0;...
43 -1 -1 -1 -1 66 -1 41 -1 -1 -1 26 7 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 0];
end
if (abs(rate -2/3) <epsilon)
rt_flag=1;
if (ind ==0)
Hbm =[ 3 0 -1 -1 2 0 -1 3 7 -1 1 1 -1 -1 -1 -1 1 0 -1 -1 -1 -1 -1 -1;...
-1 -1 1 -1 36 -1 -1 34 10 -1 -1 18 2 -1 3 0 -1 0 0 -1 -1 -1 -1 -1;...
-1 -1 12 2 -1 15 -1 40 -1 3 -1 15 -1 2 13 -1 -1 -1 0 0 -1 -1 -1 -1;...
-1 -1 19 24 -1 3 0 -1 6 -1 17 -1 -1 -1 8 39 -1 -1 -1 0 0 -1 -1 -1;...
20 -1 6 -1 -1 10 29 -1 -1 28 -1 14 -1 38 -1 -1 0 -1 -1 -1 0 0 -1 -1;...
-1 -1 10 -1 28 20 -1 -1 8 -1 36 -1 9 -1 21 45 -1 -1 -1 -1 -1 0 0 -1;...
35 25 -1 37 -1 21 -1 -1 5 -1 -1 0 -1 4 20 -1 -1 -1 -1 -1 -1 -1 0 0;...
-1 6 6 -1 -1 -1 4 -1 14 30 -1 3 36 -1 14 -1 1 -1 -1 -1 -1 -1 -1 0];
elseif (ind ==1)
Hbm =[2 -1 19 -1 47 -1 48 -1 36 -1 82 -1 47 -1 15 -1 95 0 -1 -1 -1 -1 -1 -1;...
-1 69 -1 88 -1 33 -1 3 -1 16 -1 37 -1 40 -1 48 -1 0 0 -1 -1 -1 -1 -1;...
10 -1 86 -1 62 -1 28 -1 85 -1 16 -1 34 -1 73 -1 -1 -1 0 0 -1 -1 -1 -1;...
-1 28 -1 32 -1 81 -1 27 -1 88 -1 5 -1 56 -1 37 -1 -1 -1 0 0 -1 -1 -1 ;...
23 -1 29 -1 15 -1 30 -1 66 -1 24 -1 50 -1 62 -1 -1 -1 -1 -1 0 0 -1 -1;...
-1 30 -1 65 -1 54 -1 14 -1 0 -1 30 -1 74 -1 0 -1 -1 -1 -1 -1 0 0 -1;...
32 -1 0 -1 15 -1 56 -1 85 -1 5 -1 6 -1 52 -1 0 -1 -1 -1 -1 -1 0 0;...
-1 0 -1 47 -1 13 -1 61 -1 84 -1 55 -1 78 -1 41 95 -1 -1 -1 -1 -1 -1 0];
end
end
if (abs(rate-3/4)<epsilon)
rt_flag=1;
if (ind ==0)
Hbm=[6 38 3 93 -1 -1 -1 30 70 -1 86 -1 37 38 4 11 -1 46 48 0 -1 -1 -1 -1;...
62 94 19 84 -1 92 78 -1 15 -1 -1 92 -1 45 24 32 30 -1 -1 0 0 -1 -1 -1;...
71 -1 55 -1 12 66 45 79 -1 78 -1 -1 10 -1 22 55 70 82 -1 -1 0 0 -1 -1;...
38 61 -1 66 9 73 47 64 -1 39 61 43 -1 -1 -1 -1 95 32 0 -1 -1 0 0 -1;...
-1 -1 -1 -1 32 52 55 80 95 22 6 51 24 90 44 20 -1 -1 -1 -1 -1 -1 0 0;...
-1 63 31 88 20 -1 -1 -1 6 40 56 16 71 53 -1 -1 27 26 48 -1 -1 -1 -1 0];
elseif (ind ==1)
Hbm= [-1 81 -1 28 -1 -1 14 25 17 -1 -1 85 29 52 78 95 22 92 0 0 -1 -1 -1 -1;...
42 -1 14 68 32 -1 -1 -1 -1 70 43 11 36 40 33 57 38 24 -1 0 0 -1 -1 -1;...
-1 -1 20 -1 -1 63 39 -1 70 67 -1 38 4 72 47 29 60 5 80 -1 0 0 -1 -1;...
64 2 -1 -1 63 -1 -1 3 51 -1 81 15 94 9 85 36 14 19 -1 -1 -1 0 0 -1;...
-1 53 60 80 -1 26 75 -1 -1 -1 -1 86 77 1 3 72 60 25 -1 -1 -1 -1 0 0;...
77 -1 -1 -1 15 28 -1 38 -1 72 30 68 85 84 26 64 11 89 0 -1 -1 -1 -1 0];
end
end
if (abs(rate-5/6)<epsilon)
rt_flag=1;
Hbm= [1 25 55 -1 47 4 -1 91 84 8 86 52 82 33 5 0 36 20 4 77 80 0 -1 -1;...
-1 6 -1 36 40 47 12 79 47 -1 41 21 12 71 14 72 0 44 49 0 0 0 0 -1;...
51 81 83 4 67 -1 21 -1 31 24 91 61 81 9 86 78 60 88 67 15 -1 -1 0 0;...
50 -1 50 15 -1 36 13 10 11 20 53 90 29 92 57 30 84 92 11 66 80 -1 -1 0];
end
if (rt_flag ==0)
error('This rate is not supported');
end
if(length(find(nldpc==[576:96:2304]))~=1)
error('This codeword length is not supported');
end
z =nldpc/24;
z0 =96;
[m, n]= size(Hbm);
row_ind=zeros(1,n);
col_ind=zeros(1,m);
cnt1=1;
for i=1:m
row_ind(i) =length( find(Hbm(i, :)~=-1));
cnt2=1;
for j=1:n
col_ind(j) =length( find(Hbm(:, j)~=-1));
if (Hbm(i,j) ==-1)
H(cnt1:cnt1+z-1, cnt2:cnt2+z-1)= zeros(z,z);
end
if (Hbm(i, j) ==0)
H(cnt1:cnt1+z-1, cnt2:cnt2+z-1)= eye(z);
end
if (Hbm(i, j) >0)
if ((rate ==2/3)&(ind ==0))
H(cnt1:cnt1+z-1, cnt2:cnt2+z-1)=circshift( eye(z),[0,mod(Hbm(i,j),z)]);
else
H(cnt1:cnt1+z-1, cnt2:cnt2+z-1)= circshift( eye(z),[0,floor(Hbm(i,j)*z/z0)]);
end
end
cnt2=cnt2+z;
end
cnt1=cnt1+z;
end
P =eye(z);
if ((rate ==3/4) & (ind ==1))
P=inv(circshift( eye(z),[0,floor(80*z/z0)]));
end
[mldpc, nldpc]=size(H);
H_rows=zeros(mldpc, max(row_ind)-2);
H_cols=zeros((nldpc-mldpc)+z , max(col_ind));
for i=1:mldpc
[a,b]=find(H(i,1:(nldpc-mldpc)+z)==1);
H_rows(i,1:length(b))=[b];
end
for i=1:(nldpc-mldpc)+z
[a1,b1]=find(H(:,i)==1);
H_cols(i,1:length(b1))=[a1'];
end
|
github
|
ga96jul/Bachelarbeit-master
|
matlab2tikz.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/matlab2tikz.m
| 279,997 |
utf_8
|
a05a51eb4c17b2a905ade344821248c2
|
function matlab2tikz(varargin)
%MATLAB2TIKZ Save figure in native LaTeX (TikZ/Pgfplots).
% MATLAB2TIKZ() saves the current figure as LaTeX file.
% MATLAB2TIKZ comes with several options that can be combined at will.
%
% MATLAB2TIKZ(FILENAME,...) or MATLAB2TIKZ('filename',FILENAME,...)
% stores the LaTeX code in FILENAME.
%
% MATLAB2TIKZ('filehandle',FILEHANDLE,...) stores the LaTeX code in the file
% referenced by FILEHANDLE. (default: [])
%
% MATLAB2TIKZ('figurehandle',FIGUREHANDLE,...) explicitly specifies the
% handle of the figure that is to be stored. (default: gcf)
%
% MATLAB2TIKZ('colormap',DOUBLE,...) explicitly specifies the colormap to be
% used. (default: current color map)
%
% MATLAB2TIKZ('strict',BOOL,...) tells MATLAB2TIKZ to adhere to MATLAB(R)
% conventions wherever there is room for relaxation. (default: false)
%
% MATLAB2TIKZ('strictFontSize',BOOL,...) retains the exact font sizes
% specified in MATLAB for the TikZ code. This goes against normal LaTeX
% practice. (default: false)
%
% MATLAB2TIKZ('showInfo',BOOL,...) turns informational output on or off.
% (default: true)
%
% MATLAB2TIKZ('showWarnings',BOOL,...) turns warnings on or off.
% (default: true)
%
% MATLAB2TIKZ('imagesAsPng',BOOL,...) stores MATLAB(R) images as (lossless)
% PNG files. This is more efficient than storing the image color data as TikZ
% matrix. (default: true)
%
% MATLAB2TIKZ('externalData',BOOL,...) stores all data points in external
% files as tab separated values (TSV files). (default: false)
%
% MATLAB2TIKZ('dataPath',CHAR, ...) defines where external data files
% and/or PNG figures are saved. It can be either an absolute or a relative
% path with respect to your MATLAB work directory. By default, data files are
% placed in the same directory as the TikZ output file. To place data files
% in your MATLAB work directory, you can use '.'. (default: [])
%
% MATLAB2TIKZ('relativeDataPath',CHAR, ...) tells MATLAB2TIKZ to use the
% given path to follow the external data files and PNG files. This is the
% relative path from your main LaTeX file to the data file directory.
% By default the same directory is used as the output (default: [])
%
% MATLAB2TIKZ('height',CHAR,...) sets the height of the image. This can be
% any LaTeX-compatible length, e.g., '3in' or '5cm' or '0.5\textwidth'. If
% unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('width',CHAR,...) sets the width of the image.
% If unspecified, MATLAB2TIKZ tries to make a reasonable guess.
%
% MATLAB2TIKZ('noSize',BOOL,...) determines whether 'width', 'height', and
% 'scale only axis' are specified in the generated TikZ output. For compatibility with the
% tikzscale package set this to true. (default: false)
%
% MATLAB2TIKZ('extraCode',CHAR or CELLCHAR,...) explicitly adds extra code
% at the beginning of the output file. (default: [])
%
% MATLAB2TIKZ('extraCodeAtEnd',CHAR or CELLCHAR,...) explicitly adds extra
% code at the end of the output file. (default: [])
%
% MATLAB2TIKZ('extraAxisOptions',CHAR or CELLCHAR,...) explicitly adds extra
% options to the Pgfplots axis environment. (default: [])
%
% MATLAB2TIKZ('extraColors', {{'name',[R G B]}, ...} , ...) adds
% user-defined named RGB-color definitions to the TikZ output.
% R, G and B are expected between 0 and 1. (default: {})
%
% MATLAB2TIKZ('extraTikzpictureOptions',CHAR or CELLCHAR,...)
% explicitly adds extra options to the tikzpicture environment. (default: [])
%
% MATLAB2TIKZ('encoding',CHAR,...) sets the encoding of the output file.
%
% MATLAB2TIKZ('floatFormat',CHAR,...) sets the format used for float values.
% You can use this to decrease the file size. (default: '%.15g')
%
% MATLAB2TIKZ('maxChunkLength',INT,...) sets maximum number of data points
% per \addplot for line plots (default: 4000)
%
% MATLAB2TIKZ('parseStrings',BOOL,...) determines whether title, axes labels
% and the like are parsed into LaTeX by MATLAB2TIKZ's parser.
% If you want greater flexibility, set this to false and use straight LaTeX
% for your labels. (default: true)
%
% MATLAB2TIKZ('parseStringsAsMath',BOOL,...) determines whether to use TeX's
% math mode for more characters (e.g. operators and figures). (default: false)
%
% MATLAB2TIKZ('showHiddenStrings',BOOL,...) determines whether to show
% strings whose were deliberately hidden. This is usually unnecessary, but
% can come in handy for unusual plot types (e.g., polar plots). (default:
% false)
%
% MATLAB2TIKZ('interpretTickLabelsAsTex',BOOL,...) determines whether to
% interpret tick labels as TeX. MATLAB(R) doesn't allow to do that in R2014a
% or before. In R2014b and later, please set the "TickLabelInterpreter"
% property of the relevant axis to get the same effect. (default: false)
%
% MATLAB2TIKZ('arrowHeadSize', FLOAT, ...) allows to resize the arrow heads
% in quiver plots by rescaling the arrow heads by a positive scalar. (default: 10)
%
% MATLAB2TIKZ('tikzFileComment',CHAR,...) adds a custom comment to the header
% of the output file. (default: '')
%
% MATLAB2TIKZ('addLabels',BOOL,...) add labels to plots: using Tag property
% or automatic names (where applicable) which make it possible to refer to
% them using \ref{...} (e.g., in the caption of a figure). (default: false)
%
% MATLAB2TIKZ('standalone',BOOL,...) determines whether to produce
% a standalone compilable LaTeX file. Setting this to true may be useful for
% taking a peek at what the figure will look like. (default: false)
%
% MATLAB2TIKZ('checkForUpdates',BOOL,...) determines whether to automatically
% check for updates of matlab2tikz. (default: true (if not using git))
%
% MATLAB2TIKZ('semanticLineWidths',CELLMATRIX,...) allows you to customize
% the mapping of semantic "line width" values.
% A valid entry is an Nx2 cell array:
% - the first column contains the semantic names,
% - the second column contains the corresponding line widths in points.
% The entries you provide are used in addition to the pgf defaults:
% {'ultra thin', 0.1; 'very thin' , 0.2; 'thin', 0.4; 'semithick', 0.6;
% 'thick' , 0.8; 'very thick', 1.2; 'ultra thick', 1.6}
% or a single "NaN" can be provided to turn off this feature alltogether.
% If you specify the default names, their mapping will be overwritten.
% Inside your LaTeX document, you are responsible to make sure these TikZ
% styles are properly defined.
% (Default: NaN)
%
% Example
% x = -pi:pi/10:pi;
% y = tan(sin(x)) - sin(tan(x));
% plot(x,y,'--rs');
% matlab2tikz('myfile.tex');
%
% See also: cleanfigure
%% Check if we are in MATLAB or Octave.
minimalVersion = struct('MATLAB', struct('name','2014a', 'num',[8 3]), ...
'Octave', struct('name','3.8', 'num',[3 8]));
checkDeprecatedEnvironment(minimalVersion);
m2t.args = []; % For command line arguments
m2t.current = []; % For currently active objects
m2t.transform = []; % For hgtransform groups
m2t.pgfplotsVersion = [1,3];
m2t.about.name = 'matlab2tikz';
m2t.about.version = '1.1.0';
m2t.about.years = '2008--2016';
m2t.about.website = 'http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz-matlab2tikz';
m2t.about.github = 'https://github.com/matlab2tikz/matlab2tikz';
m2t.about.wiki = [m2t.about.github '/wiki'];
m2t.about.issues = [m2t.about.github '/issues'];
m2t.about.develop = [m2t.about.github '/tree/develop'];
VCID = VersionControlIdentifier();
m2t.about.versionFull = strtrim(sprintf('v%s %s', m2t.about.version, VCID));
m2t.tol = 1.0e-15; % numerical tolerance (e.g. used to test equality of doubles)
% the actual contents of the TikZ file go here
m2t.content = struct('name', '', ...
'comment', [], ...
'options', {opts_new()}, ...
'content', {cell(0)}, ...
'children', {cell(0)});
m2t.preamble = sprintf(['\\usepackage[T1]{fontenc}\n', ...
'\\usepackage[utf8]{inputenc}\n', ...
'\\usepackage{pgfplots}\n', ...
'\\usepackage{grffile}\n', ...
'\\pgfplotsset{compat=newest}\n', ...
'\\usetikzlibrary{plotmarks}\n', ...
'\\usetikzlibrary{arrows.meta}\n', ...
'\\usepgfplotslibrary{patchplots}\n', ...
'\\usepackage{amsmath}\n']);
%% scan the options
ipp = m2tInputParser;
ipp = ipp.addOptional(ipp, 'filename', '', @(x) filenameValidation(x,ipp));
ipp = ipp.addOptional(ipp, 'filehandle', [], @filehandleValidation);
ipp = ipp.addParamValue(ipp, 'figurehandle', get(0,'CurrentFigure'), @ishandle);
ipp = ipp.addParamValue(ipp, 'colormap', [], @isnumeric);
ipp = ipp.addParamValue(ipp, 'strict', false, @islogical);
ipp = ipp.addParamValue(ipp, 'strictFontSize', false, @islogical);
ipp = ipp.addParamValue(ipp, 'showInfo', true, @islogical);
ipp = ipp.addParamValue(ipp, 'showWarnings', true, @islogical);
ipp = ipp.addParamValue(ipp, 'checkForUpdates', isempty(VCID), @islogical);
ipp = ipp.addParamValue(ipp, 'semanticLineWidths', NaN, @isValidSemanticLineWidthDefinition);
ipp = ipp.addParamValue(ipp, 'encoding' , '', @ischar);
ipp = ipp.addParamValue(ipp, 'standalone', false, @islogical);
ipp = ipp.addParamValue(ipp, 'tikzFileComment', '', @ischar);
ipp = ipp.addParamValue(ipp, 'extraColors', {}, @isColorDefinitions);
ipp = ipp.addParamValue(ipp, 'extraCode', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraCodeAtEnd', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraAxisOptions', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'extraTikzpictureOptions', {}, @isCellOrChar);
ipp = ipp.addParamValue(ipp, 'floatFormat', '%.15g', @ischar);
ipp = ipp.addParamValue(ipp, 'automaticLabels', false, @islogical);
ipp = ipp.addParamValue(ipp, 'addLabels', false, @islogical);
ipp = ipp.addParamValue(ipp, 'showHiddenStrings', false, @islogical);
ipp = ipp.addParamValue(ipp, 'height', '', @ischar);
ipp = ipp.addParamValue(ipp, 'width' , '', @ischar);
ipp = ipp.addParamValue(ipp, 'imagesAsPng', true, @islogical);
ipp = ipp.addParamValue(ipp, 'externalData', false, @islogical);
ipp = ipp.addParamValue(ipp, 'dataPath', '', @ischar);
ipp = ipp.addParamValue(ipp, 'relativeDataPath', '', @ischar);
ipp = ipp.addParamValue(ipp, 'noSize', false, @islogical);
ipp = ipp.addParamValue(ipp, 'arrowHeadSize', 10, @(x) x>0);
% Maximum chunk length.
% TeX parses files line by line with a buffer of size buf_size. If the
% plot has too many data points, pdfTeX's buffer size may be exceeded.
% As a work-around, the plot is split into several smaller chunks.
%
% What is a "large" array?
% TeX parser buffer is buf_size=200 000 char on Mac TeXLive, let's say
% 100 000 to be on the safe side.
% 1 point is represented by 25 characters (estimation): 2 coordinates (10
% char), 2 brackets, comma and white space, + 1 extra char.
% That gives a magic arbitrary number of 4000 data points per array.
ipp = ipp.addParamValue(ipp, 'maxChunkLength', 4000, @isnumeric);
% By default strings like axis labels are parsed to match the appearance of
% strings as closely as possible to that generated by MATLAB.
% If the user wants to have particular strings in the matlab2tikz output that
% can't be generated in MATLAB, they can disable string parsing. In that case
% all strings are piped literally to the LaTeX output.
ipp = ipp.addParamValue(ipp, 'parseStrings', true, @islogical);
% In addition to regular string parsing, an additional stage can be enabled
% which uses TeX's math mode for more characters like figures and operators.
ipp = ipp.addParamValue(ipp, 'parseStringsAsMath', false, @islogical);
% As opposed to titles, axis labels and such, MATLAB(R) does not interpret tick
% labels as TeX. matlab2tikz retains this behavior, but if it is desired to
% interpret the tick labels as TeX, set this option to true.
ipp = ipp.addParamValue(ipp, 'interpretTickLabelsAsTex', false, @islogical);
%% deprecated parameters (will auto-generate warnings upon parse)
ipp = ipp.addParamValue(ipp, 'relativePngPath', '', @ischar);
ipp = ipp.deprecateParam(ipp, 'relativePngPath', 'relativeDataPath');
ipp = ipp.deprecateParam(ipp, 'automaticLabels', 'addLabels');
%% Finally parse all the arguments
ipp = ipp.parse(ipp, varargin{:});
m2t.args = ipp.Results; % store the input arguments back into the m2t data struct
%% Inform users of potentially dangerous options
warnAboutParameter(m2t, 'parseStringsAsMath', @(opt)(opt==true), ...
['This may produce undesirable string output. For full control over output\n', ...
'strings please set the parameter "parseStrings" to false.']);
warnAboutParameter(m2t, 'noSize', @(opt)(opt==true), ...
'This may impede both axes sizing and placement!');
warnAboutParameter(m2t, 'imagesAsPng', @(opt)(opt==false), ...
['It is highly recommended to use PNG data to store images.\n', ...
'Make sure to set "imagesAsPng" to true.']);
%% Do some global initialization
m2t.color = configureColors(m2t.args.extraColors);
m2t.semantic.LineWidth = configureSemanticLineWidths(m2t.args.semanticLineWidths);
% define global counter variables
m2t.count.pngFile = 0; % number of PNG files
m2t.count.tsvFile = 0; % number of TSV files
m2t.count.autolabel = 0; % number of automatic labels
m2t.count.plotyylabel = 0; % number of plotyy labels
%% shortcut
m2t.ff = m2t.args.floatFormat;
%% add global elements
if isempty(m2t.args.figurehandle)
error('matlab2tikz:figureNotFound','MATLAB figure not found.');
end
m2t.current.gcf = m2t.args.figurehandle;
if m2t.args.colormap
m2t.current.colormap = m2t.args.colormap;
else
m2t.current.colormap = get(m2t.current.gcf, 'colormap');
end
%% handle output file handle/file name
[m2t, fid, fileWasOpen] = openFileForOutput(m2t);
% By default, reference the PNG (if required) from the TikZ file
% as the file path of the TikZ file itself. This works if the MATLAB script
% is executed in the same folder where the TeX file sits.
if isempty(m2t.args.relativeDataPath)
if ~isempty(m2t.args.relativePngPath)
%NOTE: eventually break backwards compatibility of relative PNG path
m2t.relativeDataPath = m2t.args.relativePngPath;
userWarning(m2t, ['Using "relativePngPath" for "relativeDataPath".', ...
' This will stop working in a future release.']);
else
m2t.relativeDataPath = m2t.args.relativeDataPath;
end
else
m2t.relativeDataPath = m2t.args.relativeDataPath;
end
if isempty(m2t.args.dataPath)
m2t.dataPath = fileparts(m2t.tikzFileName);
else
m2t.dataPath = m2t.args.dataPath;
end
%% print some version info to the screen
userInfo(m2t, ['(To disable info messages, pass [''showInfo'', false] to matlab2tikz.)\n', ...
'(For all other options, type ''help matlab2tikz''.)\n']);
userInfo(m2t, '\nThis is %s %s.\n', m2t.about.name, m2t.about.versionFull)
% In Octave, put a new line and some spaces in between the URLs for clarity.
% In MATLAB this is not necessary, since the URLs get (shorter) descriptions.
sep = switchMatOct('', sprintf('\n '));
versionInfo = ['The latest developments can be retrieved from %s.\n', ...
'You can find more documentation on %s and %s.\n', ...
'If you encounter bugs or want a new feature, go to %s.\n', ...
'Please visit %s to rate %s or download the stable release.\n'];
userInfo(m2t, versionInfo, ...
clickableUrl(m2t.about.develop, 'our development branch'), ...
[sep clickableUrl(m2t.about.github, 'our GitHub page') sep], ...
[sep clickableUrl(m2t.about.wiki, 'wiki')], ...
[sep clickableUrl(m2t.about.issues, 'our issue tracker')],...
[clickableUrl(m2t.about.website, 'FileExchange') sep],...
m2t.about.name);
%% Save the figure as TikZ to file
m2t = saveToFile(m2t, fid, fileWasOpen);
%% Check for a new matlab2tikz version outside version control
if m2t.args.checkForUpdates
m2tUpdater(m2t.about, m2t.args.showInfo);
end
end
% ==============================================================================
function [m2t, counterValue] = incrementGlobalCounter(m2t, counterName)
% Increments a global counter value and returns its value
m2t.count.(counterName) = m2t.count.(counterName) + 1;
counterValue = m2t.count.(counterName);
end
% ==============================================================================
function colorConfig = configureColors(extraColors)
% Sets the global color options for matlab2tikz
colorConfig = struct();
% Set the color resolution.
colorConfig.depth = 48; %[bit] RGB color depth (typical values: 24, 30, 48)
colorConfig.precision = 2^(-colorConfig.depth/3);
colorConfig.format = sprintf('%%0.%df',ceil(-log10(colorConfig.precision)));
% The following color RGB-values which will need to be defined:
%
% - 'extraNames' contains their designated names,
% - 'extraSpecs' their RGB specifications.
[colorConfig.extraNames, colorConfig.extraSpecs] = ...
dealColorDefinitions(extraColors);
end
% ==============================================================================
function [m2t, fid, fileWasOpen] = openFileForOutput(m2t)
% opens the output file and/or show a dialog to select one
if ~isempty(m2t.args.filehandle)
fid = m2t.args.filehandle;
fileWasOpen = true;
if ~isempty(m2t.args.filename)
userWarning(m2t, ...
'File handle AND file name for output given. File handle used, file name discarded.')
end
m2t.tikzFileName = fopen(fid);
else
fid = [];
fileWasOpen = false;
% set filename
if ~isempty(m2t.args.filename)
filename = m2t.args.filename;
else
[filename, pathname] = uiputfile({'*.tex;*.tikz'; '*.*'}, 'Save File');
filename = fullfile(pathname, filename);
end
m2t.tikzFileName = filename;
end
end
% ==============================================================================
function l = filenameValidation(x, p)
% is the filename argument NOT another keyword?
l = ischar(x) && ~any(strcmp(x,p.Parameters)); %FIXME: See #471
end
% ==============================================================================
function l = filehandleValidation(x)
% is the filehandle the handle to an opened file?
l = isnumeric(x) && any(x==fopen('all'));
end
% ==============================================================================
function bool = isCellOrChar(x)
bool = iscell(x) || ischar(x);
end
% ==============================================================================
function bool = isRGBTuple(color)
% Returns true when the color is a valid RGB tuple
bool = numel(color) == 3 && ...
all(isreal(color)) && ...
all( 0<=color & color<=1 ); % this also disallows NaN entries
end
% ==============================================================================
function bool = isColorDefinitions(colors)
% Returns true when the input is a cell array of color definitions, i.e.
% a cell array with in each cell a cell of the form {'name', [R G B]}
isValidEntry = @(e)( iscell(e) && ischar(e{1}) && isRGBTuple(e{2}) );
bool = iscell(colors) && all(cellfun(isValidEntry, colors));
end
% ==============================================================================
function bool = isValidSemanticLineWidthDefinition(defMat)
% Returns true when the input is a cell array of shape Nx2 and
% contents in each column a set of string and numerical value as needed
% for the semanticLineWidth option.
bool = iscell(defMat) && size(defMat, 2) == 2; % Nx2 cell array
bool = bool && all(cellfun(@ischar , defMat(:,1))); % first column: names
bool = bool && all(cellfun(@isnumeric, defMat(:,2))); % second column: line width in points
% alternatively: just 1 NaN to remove the defaults
bool = bool || (numel(defMat)==1 && isnan(defMat));
end
% ==============================================================================
function fid = fileOpenForWrite(m2t, filename)
% Set the encoding of the output file.
% Currently only MATLAB supports different encodings.
fid = -1;
[filepath] = fileparts(filename);
if ~exist(filepath,'dir') && ~isempty(filepath)
mkdir(filepath);
end
switch getEnvironment()
case 'MATLAB'
fid = fopen(filename, 'w', ...
'native', m2t.args.encoding);
case 'Octave'
fid = fopen(filename, 'w');
otherwise
errorUnknownEnvironment();
end
if fid == -1
error('matlab2tikz:fileOpenError', ...
'Unable to open file ''%s'' for writing.', filename);
end
end
% ==============================================================================
function path = TeXpath(path)
path = strrep(path, filesep, '/');
% TeX uses '/' as a file separator (as UNIX). Windows, however, uses
% '\' which is not supported by TeX as a file separator
end
% ==============================================================================
function m2t = saveToFile(m2t, fid, fileWasOpen)
% Save the figure as TikZ to a file. All other routines are called from here.
% get all axes handles
[m2t, axesHandles] = findPlotAxes(m2t, m2t.current.gcf);
% Turn around the handles vector to make sure that plots that appeared
% first also appear first in the vector. This makes sure the z-order of
% superimposed axes is respected and is fundamental for plotyy.
axesHandles = axesHandles(end:-1:1);
% Alternative Positioning of axes.
% Select relevant Axes and draw them.
[m2t, axesBoundingBox] = getRelevantAxes(m2t, axesHandles);
m2t.axesBoundingBox = axesBoundingBox;
m2t.axes = {};
for relevantAxesHandle = m2t.relevantAxesHandles(:)'
m2t = drawAxes(m2t, relevantAxesHandle);
end
% Handle color bars.
for cbar = m2t.cbarHandles(:)'
m2t = handleColorbar(m2t, cbar);
end
% Draw annotations
m2t = drawAnnotations(m2t);
% Add all axes containers to the file contents.
for axesContainer = m2t.axes
m2t.content = addChildren(m2t.content, axesContainer);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% actually print the stuff
minimalPgfplotsVersion = formatPgfplotsVersion(m2t.pgfplotsVersion);
m2t.content.comment = sprintf('This file was created by %s.\n', m2t.about.name);
if m2t.args.showInfo
% disable this info if showInfo=false
m2t.content.comment = [m2t.content.comment, ...
sprintf(['\n',...
'The latest updates can be retrieved from\n', ...
' %s\n', ...
'where you can also make suggestions and rate %s.\n'], ...
m2t.about.website, m2t.about.name ) ...
];
end
userInfo(m2t, 'You will need pgfplots version %s or newer to compile the TikZ output.',...
minimalPgfplotsVersion);
% Add custom comment.
if ~isempty(m2t.args.tikzFileComment)
m2t.content.comment = [m2t.content.comment, ...
sprintf('\n%s\n', m2t.args.tikzFileComment)
];
end
m2t.content.name = 'tikzpicture';
% Add custom TikZ options if any given.
m2t.content.options = opts_append_userdefined(m2t.content.options, ...
m2t.args.extraTikzpictureOptions);
m2t.content.colors = generateColorDefinitions(m2t.color);
% Open file if was not open
if ~fileWasOpen
fid = fileOpenForWrite(m2t, m2t.tikzFileName);
finally_fclose_fid = onCleanup(@() fclose(fid));
end
% Finally print it to the file
addComments(fid, m2t.content.comment);
addStandalone(m2t, fid, 'preamble');
addCustomCode(fid, '', m2t.args.extraCode, '');
addStandalone(m2t, fid, 'begin');
printAll(m2t, m2t.content, fid); % actual plotting happens here
addCustomCode(fid, '\n', m2t.args.extraCodeAtEnd, '');
addStandalone(m2t, fid, 'end');
end
% ==============================================================================
function addStandalone(m2t, fid, part)
% writes a part of a standalone LaTeX file definition
if m2t.args.standalone
switch part
case 'preamble'
fprintf(fid, '\\documentclass[tikz]{standalone}\n%s\n', m2t.preamble);
case 'begin'
fprintf(fid, '\\begin{document}\n');
case 'end'
fprintf(fid, '\n\\end{document}');
otherwise
error('m2t:unknownStandalonePart', ...
'Unknown standalone part "%s"', part);
end
end
end
% ==============================================================================
function str = generateColorDefinitions(colorConfig)
% Output the color definitions to LaTeX
str = '';
names = colorConfig.extraNames;
specs = colorConfig.extraSpecs;
ff = colorConfig.format;
if ~isempty(names)
colorDef = cell(1, length(names));
for k = 1:length(names)
% Append with '%' to avoid spacing woes in LaTeX
FORMAT = ['\\definecolor{%s}{rgb}{' ff ',' ff ',' ff '}%%\n'];
colorDef{k} = sprintf(FORMAT, names{k}, specs{k});
end
str = m2tstrjoin([colorDef, sprintf('%%\n')], '');
end
end
% ==============================================================================
function [m2t, axesHandles] = findPlotAxes(m2t, fh)
% find axes handles that are not legends/colorbars
% store detected legends and colorbars in 'm2t'
% fh figure handle
axesHandles = findall(fh, 'type', 'axes');
% Remove all legend handles, as they are treated separately.
if ~isempty(axesHandles)
% TODO fix for octave
tagKeyword = switchMatOct('Tag', 'tag');
% Find all legend handles. This is MATLAB-only.
m2t.legendHandles = findall(fh, tagKeyword, 'legend');
m2t.legendHandles = m2t.legendHandles(:)';
idx = ~ismember(axesHandles, m2t.legendHandles);
axesHandles = axesHandles(idx);
end
% Remove all colorbar handles, as they are treated separately.
if ~isempty(axesHandles)
colorbarKeyword = switchMatOct('Colorbar', 'colorbar');
% Find all colorbar handles. This is MATLAB-only.
cbarHandles = findall(fh, tagKeyword, colorbarKeyword);
% Octave also finds text handles here; no idea why. Filter.
m2t.cbarHandles = [];
for h = cbarHandles(:)'
if any(strcmpi(get(h, 'Type'),{'axes','colorbar'}))
m2t.cbarHandles = [m2t.cbarHandles, h];
end
end
m2t.cbarHandles = m2t.cbarHandles(:)';
idx = ~ismember(axesHandles, m2t.cbarHandles);
axesHandles = axesHandles(idx);
else
m2t.cbarHandles = [];
end
% Remove scribe layer holding annotations (MATLAB < R2014b)
m2t.scribeLayer = findall(axesHandles, 'Tag','scribeOverlay');
idx = ~ismember(axesHandles, m2t.scribeLayer);
axesHandles = axesHandles(idx);
end
% ==============================================================================
function addComments(fid, comment)
% prints TeX comments to file stream |fid|
if ~isempty(comment)
newline = sprintf('\n');
newlineTeX = sprintf('\n%%');
fprintf(fid, '%% %s\n', strrep(comment, newline, newlineTeX));
end
end
% ==============================================================================
function addCustomCode(fid, before, code, after)
if ~isempty(code)
fprintf(fid, before);
if ischar(code)
code = {code};
end
if iscellstr(code)
for str = code(:)'
fprintf(fid, '%s\n', str{1});
end
else
error('matlab2tikz:saveToFile', 'Need str or cellstr.');
end
fprintf(fid,after);
end
end
% ==============================================================================
function [m2t, pgfEnvironments] = handleAllChildren(m2t, h)
% Draw all children of a graphics object (if they need to be drawn).
% #COMPLEX: mainly a switch-case
str = '';
children = allchild(h);
% prepare cell array of pgfEnvironments
pgfEnvironments = cell(1, numel(children));
envCounter = 1;
% It's important that we go from back to front here, as this is
% how MATLAB does it, too. Significant for patch (contour) plots,
% and the order of plotting the colored patches.
for child = children(end:-1:1)'
% Check if object has legend. Some composite objects need to determine
% their status at the root level. For detailed explanations check
% getLegendEntries().
% TODO: could move this check into drawHggroup. Need to verify how
% hgtransform behaves though. (priority - LOW)
m2t = hasLegendEntry(m2t,child);
switch char(get(child, 'Type'))
% 'axes' environments are treated separately.
case 'line'
[m2t, str] = drawLine(m2t, child);
case 'patch'
[m2t, str] = drawPatch(m2t, child);
case 'image'
[m2t, str] = drawImage(m2t, child);
case {'hggroup', 'matlab.graphics.primitive.Group', ...
'scatter', 'bar', 'stair', 'stem' ,'errorbar', 'area', ...
'quiver','contour'}
[m2t, str] = drawHggroup(m2t, child);
case 'hgtransform'
% From http://www.mathworks.de/de/help/matlab/ref/hgtransformproperties.html:
% Matrix: 4-by-4 matrix
% Transformation matrix applied to hgtransform object and its
% children. The hgtransform object applies the transformation
% matrix to all its children.
% More information at http://www.mathworks.de/de/help/matlab/creating_plots/group-objects.html.
m2t.transform = get(child, 'Matrix');
[m2t, str] = handleAllChildren(m2t, child);
m2t.transform = [];
case 'surface'
[m2t, str] = drawSurface(m2t, child);
case 'text'
[m2t, str] = drawVisibleText(m2t, child);
case 'rectangle'
[m2t, str] = drawRectangle(m2t, child);
case 'histogram'
[m2t, str] = drawHistogram(m2t, child);
case guitypes()
% don't do anything for GUI objects and their children
str = '';
case 'light'
% These objects are not supported and should not/cannot be
% supported by matlab2tikz or pgfplots.
case ''
% No children found for handle. (It has only a title and/or
% labels). Carrying on as if nothing happened
otherwise
error('matlab2tikz:handleAllChildren', ...
'I don''t know how to handle this object: %s\n', ...
get(child, 'Type'));
end
% A composite object might nest handleAllChildren calls that can
% modify the m2t.currentHandleHasLegend value. Re-instate the
% legend status. For detailed explanations check getLegendEntries().
m2t = hasLegendEntry(m2t,child);
[m2t, legendLabel, labelRef] = addPlotyyReference(m2t, child);
legendInfo = addLegendInformation(m2t, child);
% Add labelRef BEFORE next plot to preserve color order
str = join(m2t, {labelRef, str, legendLabel, legendInfo}, '');
% append the environment
pgfEnvironments{envCounter} = str;
envCounter = envCounter +1;
end
end
% ==============================================================================
function [m2t, label, labelRef] = addPlotyyReference(m2t, h)
% Create labelled references to legend entries of the main plotyy axis
% This ensures we are either on the main or secondary axis
label = '';
labelRef = '';
if ~isAxisPlotyy(m2t.current.gca)
return
end
% Get current label counter
if hasPlotyyReference(m2t,h)
% Label the plot to later reference it. Only legend entries on the main
% plotyy axis will have a label
[m2t, labelNum] = incrementGlobalCounter(m2t, 'plotyylabel');
label = sprintf('\\label{%s}\n\n', plotyyLabelName(labelNum));
elseif m2t.currentHandleHasLegend && ~isempty(m2t.axes{end}.PlotyyReferences)
% We are on the secondary axis.
% We have produced a number of labels we can refer to so far.
% Also, here we have a number of references that are to be recorded.
% So, we make the last references (assuming the other ones have been
% realized already)
nReferences = numel(m2t.axes{end}.PlotyyReferences);
nLabels = m2t.count.plotyylabel;
% This is the range of labels, corresponding to the references
labelRange = (nLabels-nReferences+1):nLabels;
labelRef = cell(1, numel(labelRange));
% Create labelled references to legend entries of the main axis
for iRef = 1:nReferences
ref = m2t.axes{end}.PlotyyReferences(iRef);
lString = getLegendString(m2t,ref);
labelRef{iRef} = sprintf('\\addlegendimage{/pgfplots/refstyle=%s}\n\\addlegendentry{%s}\n',...
plotyyLabelName(labelRange(iRef)), lString);
end
labelRef = join(m2t, labelRef, '');
% Clear plotyy references. Ensures that references are created only once
m2t.axes{end}.PlotyyReferences = [];
else
% Do nothing: it's gonna be a legend entry.
% Not a label nor a referenced entry from the main axis.
end
end
% ==============================================================================
function label = plotyyLabelName(num)
% creates a LaTeX label for a plotyy trace
label = sprintf('plotyyref:leg%d', num);
end
% ==============================================================================
function legendInfo = addLegendInformation(m2t, h)
% Add the actual legend string
legendInfo = '';
if ~m2t.currentHandleHasLegend
return
end
legendString = getLegendString(m2t,h);
% We also need a legend alignment option to make multiline
% legend entries work. This is added by default in getLegendOpts().
legendInfo = sprintf('\\addlegendentry{%s}\n\n', legendString);
end
% ==============================================================================
function data = applyHgTransform(m2t, data)
if ~isempty(m2t.transform)
R = m2t.transform(1:3,1:3);
t = m2t.transform(1:3,4);
n = size(data, 1);
data = data * R' + kron(ones(n,1), t');
end
end
% ==============================================================================
function m2t = drawAxes(m2t, handle)
% Input arguments:
% handle.................The axes environment handle.
assertRegularAxes(handle);
% Initialize empty environment.
% Use a struct instead of a custom subclass of hgsetget (which would
% facilitate writing clean code) as structs are more portable (old MATLAB(R)
% versions, GNU Octave).
m2t.axes{end+1} = struct('handle', handle, ...
'name', '', ...
'comment', [], ...
'options', {opts_new()}, ...
'content', {cell(0)}, ...
'children', {cell(0)});
% update gca
m2t.current.gca = handle;
% Check if axis is 3d
% In MATLAB, all plots are treated as 3D plots; it's just the view that
% makes 2D plots appear like 2D.
m2t.axes{end}.is3D = isAxis3D(handle);
% Flag if axis contains barplot
m2t.axes{end}.barAddedAxisOption = false;
% Get legend entries
m2t.axes{end}.LegendHandle = getAssociatedLegend(m2t, handle);
m2t.axes{end}.LegendEntries = getLegendEntries(m2t);
m2t = getPlotyyReferences(m2t, handle);
m2t = retrievePositionOfAxes(m2t, handle);
m2t = addAspectRatioOptionsOfAxes(m2t, handle);
% Axis direction
for axis = 'xyz'
m2t.([axis 'AxisReversed']) = ...
strcmpi(get(handle,[upper(axis),'Dir']), 'reverse');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Add color scaling
CLimMode = get(handle,'CLimMode');
if strcmpi(CLimMode,'manual') || ~isempty(m2t.cbarHandles)
clim = caxis(handle);
m2t = m2t_addAxisOption(m2t, 'point meta min', sprintf(m2t.ff, clim(1)));
m2t = m2t_addAxisOption(m2t, 'point meta max', sprintf(m2t.ff, clim(2)));
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Recurse into the children of this environment.
[m2t, childrenEnvs] = handleAllChildren(m2t, handle);
m2t.axes{end} = addChildren(m2t.axes{end}, childrenEnvs);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% The rest of this is handling axes options.
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Get other axis options (ticks, axis color, label,...).
% This is set here such that the axis orientation indicator in m2t is set
% before -- if ~isVisible(handle) -- the handle's children are called.
[m2t, xopts] = getAxisOptions(m2t, handle, 'x');
[m2t, yopts] = getAxisOptions(m2t, handle, 'y');
m2t.axes{end}.options = opts_merge(m2t.axes{end}.options, xopts, yopts);
m2t = add3DOptionsOfAxes(m2t, handle);
if ~isVisible(handle)
% Setting hide{x,y} axis also hides the axis labels in Pgfplots whereas
% in MATLAB, they may still be visible. Instead use the following.
m2t = m2t_addAxisOption(m2t, 'axis line style', '{draw=none}');
m2t = m2t_addAxisOption(m2t, 'ticks', 'none');
% % An invisible axes container *can* have visible children, so don't
% % immediately bail out here.
% children = allchild(handle);
% for child = children(:)'
% if isVisible(child)
% % If the axes contain something that's visible, add an invisible
% % axes pair.
% m2t.axes{end}.name = 'axis';
% m2t.axes{end}.options = {m2t.axes{end}.options{:}, ...
% 'hide x axis', 'hide y axis'};
% NOTE: getTag was removed in 76d260d12e615602653d6f7b357393242b2430b3
% m2t.axes{end}.comment = getTag(handle);
% break;
% end
% end
% % recurse into the children of this environment
% [m2t, childrenEnvs] = handleAllChildren(m2t, handle);
% m2t.axes{end} = addChildren(m2t.axes{end}, childrenEnvs);
% return
end
m2t.axes{end}.name = 'axis';
m2t = drawBackgroundOfAxes(m2t, handle);
m2t = drawTitleOfAxes(m2t, handle);
m2t = drawBoxAndLineLocationsOfAxes(m2t, handle);
m2t = drawGridOfAxes(m2t, handle);
m2t = drawLegendOptionsOfAxes(m2t);
m2t.axes{end}.options = opts_append_userdefined(m2t.axes{end}.options, ...
m2t.args.extraAxisOptions);
end
% ==============================================================================
function m2t = drawGridOfAxes(m2t, handle)
% Draws the grids of an axis
options = opts_new();
% Check for major/minor grids
hasGrid = [isOn(get(handle, 'XGrid'));
isOn(get(handle, 'YGrid'));
isOn(get(handle, 'ZGrid')) && isAxis3D(handle)];
hasMinorGrid = [isOn(get(handle, 'XMinorGrid'));
isOn(get(handle, 'YMinorGrid'));
isOn(get(handle, 'ZMinorGrid')) && isAxis3D(handle)];
xyz = {'x', 'y', 'z'};
% Check for local grid options
% NOTE: for individual axis color options see the pfgmanual under
% major x grid style
for i=1:3
if hasGrid(i)
grid = [xyz{i}, 'majorgrids'];
options = opts_add(options, grid);
end
if hasMinorGrid(i)
grid = [xyz{i}, 'minorgrids'];
options = opts_add(options, grid);
end
end
% Check for global grid options
if any(hasGrid)
gridOpts = opts_new();
% Get the line style and translate it to pgfplots
[gridLS, isDefault] = getAndCheckDefault(...
'axes', handle, 'GridLineStyle', ':');
if ~isDefault || m2t.args.strict
gridOpts = opts_add(gridOpts, translateLineStyle(gridLS));
end
% Get the color of the grid and translate it to pgfplots usable
% values
[gridColor, defaultColor] = getAndCheckDefault(...
'axes', handle, 'GridColor', [0.15, 0.15, 0.15]);
if ~defaultColor
[m2t, gridColor] = getColor(m2t, handle, gridColor, 'patch');
gridOpts = opts_add(gridOpts, gridColor);
end
% Get the alpha of the grid and translate it to pgfplots
[gridAlpha, defaultAlpha] = getAndCheckDefault(...
'axes', handle, 'GridAlpha', 0.1);
if ~defaultAlpha
gridOpts = opts_add(gridOpts, 'opacity', num2str(gridAlpha));
end
if ~isempty(gridOpts)
options = opts_addSubOpts(options, 'grid style', gridOpts);
end
end
if any(hasMinorGrid)
minorGridOpts = opts_new();
% Get the line style and translate it to pgfplots
[minorGridLS, isDefault] = getAndCheckDefault(...
'axes', handle, 'MinorGridLineStyle', ':');
if ~isDefault || m2t.args.strict
minorGridOpts = opts_add(minorGridOpts, translateLineStyle(minorGridLS));
end
% Get the color of the grid and translate it to pgfplots usable
% values
[minorGridColor, defaultColor] = getAndCheckDefault(...
'axes', handle, 'MinorGridColor', [0.1, 0.1, 0.1]);
if ~defaultColor
[m2t, minorGridColor] = getColor(m2t, handle, minorGridColor, 'patch');
minorGridOpts = opts_add(minorGridOpts, minorGridColor);
end
% Get the alpha of the grid and translate it to pgfplots
[minorGridAlpha, defaultAlpha] = getAndCheckDefault(...
'axes', handle, 'MinorGridAlpha', 0.1);
if ~defaultAlpha
minorGridOpts = opts_add(minorGridOpts, 'opacity', num2str(minorGridAlpha));
end
if ~isempty(minorGridOpts)
options = opts_addSubOpts(options, 'minor grid style', minorGridOpts);
end
end
if ~any(hasGrid) && ~any(hasMinorGrid)
% When specifying 'axis on top', the axes stay above all graphs (which is
% default MATLAB behavior), but so do the grids (which is not default
% behavior).
%TODO: use proper grid ordering
if m2t.args.strict
options = opts_add(options, 'axis on top');
end
% FIXME: axis background, axis grid, main, axis ticks, axis lines, axis tick labels, axis descriptions, axis foreground
end
m2t.axes{end}.options = opts_merge(m2t.axes{end}.options, options);
end
% ==============================================================================
function m2t = add3DOptionsOfAxes(m2t, handle)
% adds 3D specific options of an axes object
if isAxis3D(handle)
[m2t, zopts] = getAxisOptions(m2t, handle, 'z');
m2t.axes{end}.options = opts_merge(m2t.axes{end}.options, zopts);
VIEWFORMAT = ['{' m2t.ff '}{' m2t.ff '}'];
m2t = m2t_addAxisOption(m2t, 'view', sprintf(VIEWFORMAT, get(handle, 'View')));
end
end
% ==============================================================================
function legendhandle = getAssociatedLegend(m2t, axisHandle)
% Get legend handle associated with current axis
legendhandle = [];
env = getEnvironment();
switch env
case 'Octave'
% Make sure that m2t.legendHandles is a row vector.
for lhandle = m2t.legendHandles(:)'
ud = get(lhandle, 'UserData');
% Empty if no legend and multiple handles if plotyy
if ~isempty(ud) && any(axisHandle == ud.handle)
legendhandle = lhandle;
break
end
end
case 'MATLAB'
legendhandle = legend(axisHandle);
end
% NOTE: there is a BUG in HG1 and Octave. Setting the box off sets the
% legend visibility off too. We assume the legend is visible if it has
% a visible child.
isInvisibleHG2 = isHG2() && ~isVisible(legendhandle);
isInvisibleHG1orOctave = (~isHG2() || strcmpi(env,'Octave')) &&...
~isVisibleContainer(legendhandle);
% Do not return the handle if legend is invisible
if isInvisibleHG1orOctave || isInvisibleHG2;
legendhandle = [];
end
end
% ==============================================================================
function entries = getLegendEntries(m2t)
% Retrieve the handles of the objects that have a legend entry
% Non-composite objects are straightforward, e.g. line, and have the
% legend entry at their same level, hence we return their handle.
%
% Hggroups behave differently depending on the environment and we might
% return the handle to the hgroot or to one of its children:
% 1) Matlab places the legend entry at the hgroot.
%
% Usually, the decision to place the legend is either unchanged from
% the first call to handleAllChildrena(axis) or delegated to a
% specialized drawing routine, e.g. drawContour(), if the group has to
% be drawn atomically. In this case, the legend entry stays with the
% hgroot.
%
% If the hggroup is a pure container like in a bodeplot, i.e. the
% `type` is not listed in drawHggroup(), a nested call to
% handleAllChildren(hgroot) follows. But, this second call cannot detect
% legend entries on the children. Hence, we pass down the legend entry
% from the hgroot to its first child.
%
% 2) Octave places the entry with one of the children of the hgroot.
% Hence, most of the hggroups are correctly dealt by a nested
% handleAllChildren() call which detects the entry on the child.
% However, when we can guess the type of hggroup with
% guessOctavePlotType(), the legend entry should be placed at the root
% level, hence we bubble it up from the child to the hgroot.
entries = [];
legendHandle = m2t.axes{end}.LegendHandle;
if isempty(legendHandle)
return
end
switch getEnvironment()
case 'Octave'
% See set(hlegend, "deletefcn", {@deletelegend2, ca, [], [], t1, hplots}); in legend.m
delfun = get(legendHandle,'deletefcn');
entries = delfun{6};
% Bubble-up legend entry properties from child to hggroup root
% for guessable objects
for ii = 1:numel(entries)
child = entries(ii);
anc = ancestor(child,'hggroup');
if isempty(anc) % not an hggroup
continue
end
cl = guessOctavePlotType(anc);
if ~strcmpi(cl, 'unknown') % guessable hggroup, then bubble-up
legendString = get(child,'displayname');
set(anc,'displayname',legendString);
entries(ii) = anc;
end
end
case 'MATLAB'
% Undocumented property (exists at least since 2008a)
entries = get(legendHandle,'PlotChildren');
% Take only the first child from a pure hggroup (e.g. bodeplots)
for ii = 1:numel(entries)
entry = entries(ii);
% Note that class() is not supported in Octave
isHggroupClass = strcmpi(class(handle(entry)),'hggroup');
if isHggroupClass
children = get(entry, 'Children');
firstChild = children(1);
if isnumeric(firstChild)
firstChild = handle(firstChild);
end
% Inherits DisplayName from hggroup root
set(firstChild, 'DisplayName', get(entry, 'DisplayName'));
entries(ii) = firstChild;
end
end
end
end
% ==============================================================================
function m2t = getPlotyyReferences(m2t,axisHandle)
% Retrieve references to legend entries of the main plotyy axis
%
% A plotyy plot has a main and a secondary axis. The legend is associated
% with the main axis and hence m2t will only include the legend entries
% that belong to the \axis[] that has a legend.
%
% One way to include the legend entries from the secondary axis (in the
% same legend) is to first label the \addplot[] and then reference them.
% See https://tex.stackexchange.com/questions/42697/42752#42752
%
% However, in .tex labels should come before they are referenced. Hence,
% we actually label the legend entries from the main axis and swap the
% legendhandle to the secondary axis.
%
% The legend will not be plotted with the main \axis[] and the labelled
% legend entries will be skipped until the secondary axis. Then, they will
% be listed before any legend entry from the secondary axis.
% Retrieve legend handle
if isAxisMain(axisHandle)
legendHandle = m2t.axes{end}.LegendHandle;
else
legendHandle = getAssociatedLegend(m2t,getPlotyyPeer(axisHandle));
m2t.axes{end}.LegendHandle = legendHandle;
end
% Not a plotyy axis or no legend
if ~isAxisPlotyy(axisHandle) || isempty(legendHandle)
m2t.axes{end}.PlotyyReferences = [];
elseif isAxisMain(axisHandle)
% Mark legend entries of the main axis for labelling
legendEntries = m2t.axes{end}.LegendEntries;
ancAxes = ancestor(legendEntries,'axes');
idx = ismember([ancAxes{:}], axisHandle);
m2t.axes{end}.PlotyyReferences = legendEntries(idx);
% Ensure no legend is created on the main axis
m2t.axes{end}.LegendHandle = [];
else
% Get legend entries associated to secondary plotyy axis. We can do
% this because we took the legendhandle from the peer (main axis)
legendEntries = getLegendEntries(m2t);
ancAxes = ancestor(legendEntries,'axes');
if iscell(ancAxes)
ancAxes = [ancAxes{:}];
end
idx = ismember(double(ancAxes), axisHandle);
m2t.axes{end}.LegendEntries = legendEntries(idx);
% Recover referenced legend entries of the main axis
m2t.axes{end}.PlotyyReferences = legendEntries(~idx);
end
end
% ==============================================================================
function bool = isAxisMain(h)
% Check if it is the main axis e.g. in a plotyy plot
if ~isAxisPlotyy(h)
bool = true;
return % an axis not constructed by plotyy is always(?) a main axis
end
% If it is a Plotyy axis
switch getEnvironment()
case 'Octave'
plotyyAxes = get(h, '__plotyy_axes__');
bool = find(plotyyAxes == h) == 1;
case 'MATLAB'
bool = ~isempty(getappdata(h, 'LegendPeerHandle'));
end
end
% ==============================================================================
function bool = isAxisPlotyy(h)
% Check if handle is a plotyy axis
switch getEnvironment()
case 'Octave'
% Cannot test hidden property with isfield(), is always false
try
get(h, '__plotyy_axes__');
bool = true;
catch
bool = false;
end
case 'MATLAB'
bool = ~isempty(getappdata(h, 'graphicsPlotyyPeer'));
end
end
% ==============================================================================
function peer = getPlotyyPeer(axisHandle)
% Get the other axis coupled in plotyy plots
switch getEnvironment()
case 'Octave'
plotyyAxes = get(axisHandle, '__plotyy_axes__');
peer = setdiff(plotyyAxes, axisHandle);
case 'MATLAB'
peer = getappdata(axisHandle, 'graphicsPlotyyPeer');
end
end
% ==============================================================================
function legendString = getLegendString(m2t, h)
% Retrieve the legend string for the given handle
str = getOrDefault(h, 'displayname', '');
interpreter = get(m2t.axes{end}.LegendHandle,'interpreter');
% HG1: autogenerated legend strings, i.e. data1,..., dataN, do not populate
% the 'displayname' property. Go through 'userdata'
if isempty(str)
ud = get(m2t.axes{end}.LegendHandle,'userdata');
idx = ismember(ud.handles, h);
str = ud.lstrings{idx};
end
% split string to cell, if newline character '\n' (ASCII 10) is present
delimeter = sprintf('\n');
str = regexp(str, delimeter, 'split');
str = prettyPrint(m2t, str, interpreter);
legendString = join(m2t, str, '\\');
end
% ==============================================================================
function [m2t, bool] = hasLegendEntry(m2t, h)
% Check if the handle has a legend entry and track its legend status in m2t
legendEntries = m2t.axes{end}.LegendEntries;
if isnumeric(h)
legendEntries = double(legendEntries);
end
% Should not have a legend reference
bool = any(ismember(h, legendEntries)) && ~hasPlotyyReference(m2t,h);
m2t.currentHandleHasLegend = bool;
end
% ==============================================================================
function bool = hasPlotyyReference(m2t,h)
% Check if the handle has a legend reference
plotyyReferences = m2t.axes{end}.PlotyyReferences;
if isnumeric(h)
plotyyReferences = double(plotyyReferences);
end
bool = any(ismember(h, plotyyReferences));
end
% ==============================================================================
function m2t = retrievePositionOfAxes(m2t, handle)
% This retrieves the position of an axes and stores it into the m2t data
% structure
pos = getAxesPosition(m2t, handle, m2t.args.width, ...
m2t.args.height, m2t.axesBoundingBox);
% set the width
if (~m2t.args.noSize)
% optionally prevents setting the width and height of the axis
m2t = setDimensionOfAxes(m2t, 'width', pos.w);
m2t = setDimensionOfAxes(m2t, 'height', pos.h);
m2t = m2t_addAxisOption(m2t, 'at', ...
['{(' formatDim(pos.x.value, pos.x.unit) ','...
formatDim(pos.y.value, pos.y.unit) ')}']);
% the following is general MATLAB behavior:
m2t = m2t_addAxisOption(m2t, 'scale only axis');
end
end
% ==============================================================================
function m2t = setDimensionOfAxes(m2t, widthOrHeight, dimension)
% sets the dimension "name" of the current axes to the struct "dim"
m2t = m2t_addAxisOption(m2t, widthOrHeight, ...
formatDim(dimension.value, dimension.unit));
end
% ==============================================================================
function m2t = addAspectRatioOptionsOfAxes(m2t, handle)
% Set manual aspect ratio for current axes
% TODO: deal with 'axis image', 'axis square', etc. (#540)
if strcmpi(get(handle, 'DataAspectRatioMode'), 'manual') ||...
strcmpi(get(handle, 'PlotBoxAspectRatioMode'), 'manual')
% we need to set the plot box aspect ratio
if m2t.axes{end}.is3D
% Note: set 'plot box ratio' for 3D axes to avoid bug with
% 'scale mode = uniformly' (see #560)
aspectRatio = getPlotBoxAspectRatio(handle);
m2t = m2t_addAxisOption(m2t, 'plot box ratio', ...
formatAspectRatio(m2t, aspectRatio));
end
end
end
% ==============================================================================
function m2t = drawBackgroundOfAxes(m2t, handle)
% draw the background color of the current axes
backgroundColor = get(handle, 'Color');
if ~isNone(backgroundColor) && isVisible(handle)
[m2t, col] = getColor(m2t, handle, backgroundColor, 'patch');
m2t = m2t_addAxisOption(m2t, 'axis background/.style', sprintf('{fill=%s}', col));
end
end
% ==============================================================================
function m2t = drawTitleOfAxes(m2t, handle)
% processes the title of an axes object
[m2t, m2t.axes{end}.options] = getTitle(m2t, handle, m2t.axes{end}.options);
end
% ==============================================================================
function [m2t, opts] = getTitle(m2t, handle, opts)
% gets the title and its markup from an axes/colorbar/...
[m2t, opts] = getTitleOrLabel_(m2t, handle, opts, 'Title');
end
function [m2t, opts] = getLabel(m2t, handle, opts, tikzKeyword)
% gets the label and its markup from an axes/colorbar/...
[m2t, opts] = getTitleOrLabel_(m2t, handle, opts, 'Label', tikzKeyword);
end
function [m2t, opts] = getAxisLabel(m2t, handle, axis, opts)
% convert an {x,y,z} axis label to TikZ
labelName = [upper(axis) 'Label'];
[m2t, opts] = getTitleOrLabel_(m2t, handle, opts, labelName);
end
function [m2t, opts] = getTitleOrLabel_(m2t, handle, opts, labelKind, tikzKeyword)
% gets a string element from an object
if ~exist('tikzKeyword', 'var') || isempty(tikzKeyword)
tikzKeyword = lower(labelKind);
end
object = get(handle, labelKind);
str = get(object, 'String');
if ~isempty(str)
interpreter = get(object, 'Interpreter');
str = prettyPrint(m2t, str, interpreter);
[m2t, style] = getFontStyle(m2t, object);
if length(str) > 1 %multiline
style = opts_add(style, 'align', 'center');
end
if ~isempty(style)
opts = opts_addSubOpts(opts, [tikzKeyword ' style'], style);
end
str = join(m2t, str, '\\[1ex]');
opts = opts_add(opts, tikzKeyword, sprintf('{%s}', str));
end
end
% ==============================================================================
function m2t = drawBoxAndLineLocationsOfAxes(m2t, h)
% draw the box and axis line location of an axes object
isBoxOn = isOn(get(h, 'box'));
xLoc = get(h, 'XAxisLocation');
yLoc = get(h, 'YAxisLocation');
isXaxisBottom = strcmpi(xLoc,'bottom');
isYaxisLeft = strcmpi(yLoc,'left');
% Only flip the labels to the other side if not at the default
% left/bottom positions
if isBoxOn
if ~isXaxisBottom
m2t = m2t_addAxisOption(m2t, 'xticklabel pos','right');
end
if ~isYaxisLeft
m2t = m2t_addAxisOption(m2t, 'yticklabel pos','right');
end
% Position axes lines (strips the box)
else
m2t = m2t_addAxisOption(m2t, 'axis x line*', xLoc);
m2t = m2t_addAxisOption(m2t, 'axis y line*', yLoc);
if m2t.axes{end}.is3D
% There's no such attribute as 'ZAxisLocation'.
% Instead, the default seems to be 'left'.
m2t = m2t_addAxisOption(m2t, 'axis z line*', 'left');
end
end
end
% ==============================================================================
function m2t = drawLegendOptionsOfAxes(m2t)
legendHandle = m2t.axes{end}.LegendHandle;
if isempty(legendHandle)
return
end
[m2t, key, legendOpts] = getLegendOpts(m2t, legendHandle);
m2t = m2t_addAxisOption(m2t, key, legendOpts);
end
% ==============================================================================
function m2t = handleColorbar(m2t, handle)
if isempty(handle)
return;
end
% Find the axes environment that this colorbar belongs to.
parentAxesHandle = double(get(handle,'axes'));
parentFound = false;
for k = 1:length(m2t.axes)
if m2t.axes{k}.handle == parentAxesHandle
k0 = k;
parentFound = true;
break;
end
end
if parentFound
m2t.axes{k0}.options = opts_append(m2t.axes{k0}.options, ...
matlab2pgfplotsColormap(m2t, m2t.current.colormap), []);
% Append cell string.
m2t.axes{k0}.options = cat(1, m2t.axes{k0}.options, ...
getColorbarOptions(m2t, handle));
else
warning('matlab2tikz:parentAxesOfColorBarNotFound',...
'Could not find parent axes for color bar. Skipping.');
end
end
% ==============================================================================
function [m2t, options] = getAxisOptions(m2t, handle, axis)
assertValidAxisSpecifier(axis);
options = opts_new();
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% axis colors
[color, isDfltColor] = getAndCheckDefault('Axes', handle, ...
[upper(axis),'Color'], [ 0 0 0 ]);
if ~isDfltColor || m2t.args.strict
[m2t, col] = getColor(m2t, handle, color, 'patch');
if isOn(get(handle, 'box'))
% If the axes are arranged as a box, make sure that the individual
% axes are drawn as four separate paths. This makes the alignment
% at the box corners somewhat less nice, but allows for different
% axis styles (e.g., colors).
options = opts_add(options, 'separate axis lines');
end
% set color of axis lines
options = ...
opts_add(options, ...
['every outer ', axis, ' axis line/.append style'], ...
['{', col, '}']);
% set color of tick labels
options = ...
opts_add(options, ...
['every ',axis,' tick label/.append style'], ...
['{font=\color{',col,'}}']);
% set color of ticks
options = ...
opts_add(options, ...
['every ',axis,' tick/.append style'], ...
['{',col,'}']);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% handle the orientation
isAxisReversed = strcmpi(get(handle,[upper(axis),'Dir']), 'reverse');
m2t.([axis 'AxisReversed']) = isAxisReversed;
if isAxisReversed
options = opts_add(options, [axis, ' dir'], 'reverse');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
axisScale = getOrDefault(handle, [upper(axis) 'Scale'], 'lin');
if strcmpi(axisScale, 'log');
options = opts_add(options, [axis,'mode'], 'log');
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis limits
options = setAxisLimits(m2t, handle, axis, options);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get ticks along with the labels
[options] = getAxisTicks(m2t, handle, axis, options);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get axis label
[m2t, options] = getAxisLabel(m2t, handle, axis, options);
end
% ==============================================================================
function [options] = getAxisTicks(m2t, handle, axis, options)
% Return axis tick marks Pgfplots style. Nice: Tick lengths and such
% details are taken care of by Pgfplots.
assertValidAxisSpecifier(axis);
keywordTickMode = [upper(axis), 'TickMode'];
tickMode = get(handle, keywordTickMode);
keywordTick = [upper(axis), 'Tick'];
ticks = get(handle, keywordTick);
% hidden properties are not caught by hasProperties
isDatetimeTicks = isAxisTicksDateTime(handle, axis);
if isempty(ticks)
% If no ticks are present, we need to enforce this in any case.
pgfTicks = '\empty';
elseif strcmpi(tickMode, 'auto') && ~m2t.args.strict && ~isDatetimeTicks
% Let pgfplots decide if the tickmode is auto or conversion is not
% strict and we are not dealing with datetime ticks
pgfTicks = [];
else % strcmpi(tickMode,'manual') || m2t.args.strict
pgfTicks = join(m2t, cellstr(num2str(ticks(:))), ', ');
end
keywordTickLabelMode = [upper(axis), 'TickLabelMode'];
tickLabelMode = get(handle, keywordTickLabelMode);
if strcmpi(tickLabelMode, 'auto') && ~m2t.args.strict && ~isDatetimeTicks
pgfTickLabels = [];
else % strcmpi(tickLabelMode,'manual') || m2t.args.strict
% HG2 allows to set 'TickLabelInterpreter'.
% HG1 tacitly uses the interpreter 'none'.
% See http://www.mathworks.com/matlabcentral/answers/102053#comment_300079
fallback = defaultTickLabelInterpreter(m2t);
interpreter = getOrDefault(handle, 'TickLabelInterpreter', fallback);
keywordTickLabel = [upper(axis), 'TickLabel'];
tickLabels = cellstr(get(handle, keywordTickLabel));
tickLabels = prettyPrint(m2t, tickLabels, interpreter);
keywordScale = [upper(axis), 'Scale'];
isAxisLog = strcmpi(getOrDefault(handle,keywordScale, 'lin'), 'log');
[pgfTicks, pgfTickLabels] = ...
matlabTicks2pgfplotsTicks(m2t, ticks, tickLabels, isAxisLog, tickLabelMode);
end
keywordMinorTick = [upper(axis), 'MinorTick'];
hasMinorTicks = isOn(getOrDefault(handle, keywordMinorTick, 'off'));
tickDirection = getOrDefault(handle, 'TickDir', 'in');
options = setAxisTicks(m2t, options, axis, pgfTicks, pgfTickLabels, ...
hasMinorTicks, tickDirection, isDatetimeTicks);
options = setAxisTickLabelStyle(options, axis, handle);
end
% ==============================================================================
function options = setAxisTickLabelStyle(options, axis, handle)
% determine the style of tick labels
%TODO: translate the style of tick labels fully (font?, weight, ...)
kwRotation = [upper(axis), 'TickLabelRotation'];
rotation = getOrDefault(handle, kwRotation, 0);
if rotation ~= 0
options = opts_add(options, [axis, 'ticklabel style'], ...
sprintf('{rotate=%d}', rotation));
end
end
% ==============================================================================
function interpreter = defaultTickLabelInterpreter(m2t)
% determines the default tick label interpreter
% This is only relevant in HG1/Octave. In HG2, we use the interpreter
% set in the object (not the global default).
if m2t.args.interpretTickLabelsAsTex
interpreter = 'tex';
else
interpreter = 'none';
end
end
% ==============================================================================
function isDatetimeTicks = isAxisTicksDateTime(handle, axis)
% returns true when the axis has DateTime ticks
try
% Get hidden properties of the datetime axes manager
dtsManager = get(handle, 'DatetimeDurationPlotAxesListenersManager');
oldState = warning('off','MATLAB:structOnObject');
dtsManager = struct(dtsManager);
warning(oldState);
isDatetimeTicks = dtsManager.([upper(axis) 'DateTicks']) == 1;
catch
isDatetimeTicks = false;
end
end
% ==============================================================================
function options = setAxisTicks(m2t, options, axis, ticks, tickLabels,hasMinorTicks, tickDir,isDatetimeTicks)
% set ticks options
% According to http://www.mathworks.com/help/techdoc/ref/axes_props.html,
% the number of minor ticks is automatically determined by MATLAB(R) to
% fit the size of the axis. Until we know how to extract this number, use
% a reasonable default.
matlabDefaultNumMinorTicks = 3;
if ~isempty(ticks)
options = opts_add(options, [axis,'tick'], sprintf('{%s}', ticks));
end
if ~isempty(tickLabels)
options = opts_add(options, ...
[axis,'ticklabels'], sprintf('{%s}', tickLabels));
end
if hasMinorTicks
options = opts_add(options, [axis,'minorticks'], 'true');
if m2t.args.strict
options = opts_add(options, ...
sprintf('minor %s tick num', axis), ...
sprintf('{%d}', matlabDefaultNumMinorTicks));
end
end
if strcmpi(tickDir,'out')
options = opts_add(options, 'tick align', 'outside');
elseif strcmpi(tickDir,'both')
options = opts_add(options, 'tick align', 'center');
end
if isDatetimeTicks
options = opts_add(options, ['scaled ' axis ' ticks'], 'false');
end
end
% ==============================================================================
function assertValidAxisSpecifier(axis)
% assert that axis is a valid axis specifier
if ~ismember(axis, {'x','y','z'})
error('matlab2tikz:illegalAxisSpecifier', ...
'Illegal axis specifier "%s".', axis);
end
end
% ==============================================================================
function assertRegularAxes(handle)
% assert that the (axes) object specified by handle is a regular axes and not a
% colorbar or a legend
tag = lower(get(handle,'Tag'));
if ismember(tag,{'colorbar','legend'})
error('matlab2tikz:notARegularAxes', ...
['The object "%s" is not a regular axes object. ' ...
'It cannot be handled with drawAxes!'], handle);
end
end
% ==============================================================================
function options = setAxisLimits(m2t, handle, axis, options)
% set the upper/lower limit of an axis
limits = get(handle, [upper(axis),'Lim']);
if isfinite(limits(1))
options = opts_add(options, [axis,'min'], sprintf(m2t.ff, limits(1)));
end
if isfinite(limits(2))
options = opts_add(options, [axis,'max'], sprintf(m2t.ff, limits(2)));
end
end
% ==============================================================================
function bool = isVisibleContainer(axisHandle)
if ~isVisible(axisHandle)
% An invisible axes container *can* have visible children, so don't
% immediately bail out here. Also it *can* have a visible title,
% labels or children
bool = false;
for prop = {'Children', 'Title', 'XLabel', 'YLabel', 'ZLabel'}
property = prop{1};
if strcmpi(property, 'Children')
children = allchild(axisHandle);
elseif isprop(axisHandle, property)
children = get(axisHandle, property);
else
continue; % don't check non-existent properties
end
for child = children(:)'
if isVisible(child)
bool = true;
return;
end
end
end
else
bool = true;
end
end
% ==============================================================================
function [m2t, str] = drawLine(m2t, h)
% Returns the code for drawing a regular line and error bars.
% This is an extremely common operation and takes place in most of the
% not too fancy plots.
str = '';
if ~isLineVisible(h)
return; % there is nothing to plot
end
% Color
color = get(h, 'Color');
[m2t, xcolor] = getColor(m2t, h, color, 'patch');
% Line and marker options
[m2t, lineOptions] = getLineOptions(m2t, h);
[m2t, markerOptions] = getMarkerOptions(m2t, h);
drawOptions = opts_new();
drawOptions = opts_add(drawOptions, 'color', xcolor);
drawOptions = opts_merge(drawOptions, lineOptions, markerOptions);
% Check for "special" lines, e.g.:
if strcmpi(get(h, 'Tag'), 'zplane_unitcircle')
[m2t, str] = specialDrawZplaneUnitCircle(m2t, drawOptions);
return
end
% build the data matrix
data = getXYZDataFromLine(m2t, h);
yDeviation = getYDeviations(h);
if ~isempty(yDeviation)
data = [data, yDeviation];
end
% Check if any value is infinite/NaN. In that case, add appropriate option.
m2t = jumpAtUnboundCoords(m2t, data);
[m2t, dataString] = writePlotData(m2t, data, drawOptions);
[m2t, labelString] = addLabel(m2t, h);
str = [dataString, labelString];
end
% ==============================================================================
function [m2t, str] = specialDrawZplaneUnitCircle(m2t, drawOptions)
% Draw unit circle and axes.
% TODO Don't hardcode "10", but extract from parent axes of |h|
opts = opts_print(drawOptions);
str = [sprintf('\\draw[%s] (axis cs:0,0) circle[radius=1];\n', opts), ...
sprintf('\\draw[%s] (axis cs:-10,0)--(axis cs:10,0);\n', opts), ...
sprintf('\\draw[%s] (axis cs:0,-10)--(axis cs:0,10);\n', opts)];
end
% ==============================================================================
function bool = isLineVisible(h)
% check if a line object is actually visible (has markers and so on)
lineStyle = get(h, 'LineStyle');
lineWidth = get(h, 'LineWidth');
marker = getOrDefault(h, 'Marker','none');
hasLines = ~isNone(lineStyle) && lineWidth > 0;
hasMarkers = ~isNone(marker);
hasDeviations = ~isempty(getYDeviations(h));
bool = isVisible(h) && (hasLines || hasMarkers || hasDeviations);
end
% ==============================================================================
function [m2t, str] = writePlotData(m2t, data, drawOptions)
% actually writes the plot data to file
str = '';
is3D = m2t.axes{end}.is3D;
if is3D
% Don't try to be smart in parametric 3d plots: Just plot all the data.
[m2t, table, tableOptions] = makeTable(m2t, {'','',''}, data);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot3 [%s]\n table[%s] {%s};\n ', ...
drawOpts, tabOpts, table);
else
% split the data into logical chunks
dataCell = splitLine(m2t, data);
% plot them
strPart = cell(1, length(dataCell));
for k = 1:length(dataCell)
% If the line has a legend string, make sure to only include a legend
% entry for the *last* occurrence of the plot series.
% Hence the condition k<length(xDataCell).
%if ~isempty(m2t.legendHandles) && (~m2t.currentHandleHasLegend || k < length(dataCell))
if ~m2t.currentHandleHasLegend || k < length(dataCell)
% No legend entry found. Don't include plot in legend.
hiddenDrawOptions = maybeShowInLegend(false, drawOptions);
opts = opts_print(hiddenDrawOptions);
else
opts = opts_print(drawOptions);
end
[m2t, Part] = plotLine2d(m2t, opts, dataCell{k});
strPart{k} = Part;
end
strPart = join(m2t, strPart, '');
str = [str, strPart];
end
end
% ==============================================================================
function [data] = getXYZDataFromLine(m2t, h)
% Retrieves the X, Y and Z (if appropriate) data from a Line object
%
% First put them all together in one multiarray.
% This also implicitly makes sure that the lengths match.
try
xData = get(h, 'XData');
yData = get(h, 'YData');
catch
% Line annotation
xData = get(h, 'X');
yData = get(h, 'Y');
end
is3D = m2t.axes{end}.is3D;
if ~is3D
data = [xData(:), yData(:)];
else
zData = get(h, 'ZData');
data = applyHgTransform(m2t, [xData(:), yData(:), zData(:)]);
end
end
% ==============================================================================
function [m2t, labelCode] = addLabel(m2t, h)
% conditionally add a LaTeX label after the current plot
labelCode = '';
if m2t.args.automaticLabels||m2t.args.addLabels
lineTag = get(h,'Tag');
if ~isempty(lineTag)
labelName = sprintf('%s', lineTag);
else
[pathstr, name] = fileparts(m2t.args.filename); %#ok
labelName = sprintf('addplot:%s%d', name, m2t.count.autolabel);
[m2t] = incrementGlobalCounter(m2t, 'autolabel');
% TODO: First increment the counter, then use it such that the
% pattern is the same everywhere
end
labelCode = sprintf('\\label{%s}\n', labelName);
userWarning(m2t, 'Automatically added label ''%s'' for line plot.', labelName);
end
end
% ==============================================================================
function [m2t,str] = plotLine2d(m2t, opts, data)
errorbarMode = (size(data,2) == 4); % is (optional) yDeviation given?
errorBar = '';
if errorbarMode
m2t = needsPgfplotsVersion(m2t, [1,9]);
errorBar = sprintf('plot [error bars/.cd, y dir = both, y explicit]\n');
end
% Convert to string array then cell to call sprintf once (and no loops).
[m2t, table, tableOptions] = makeTable(m2t, repmat({''}, size(data,2)), data);
if errorbarMode
tableOptions = opts_add(tableOptions, 'y error plus index', '2');
tableOptions = opts_add(tableOptions, 'y error minus index', '3');
end
% Print out
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot [%s]\n %s table[%s]{%s};\n',...
opts, errorBar, tabOpts, table);
end
% ==============================================================================
function dataCell = splitLine(m2t, data)
% TeX parses files line by line with a buffer of size buf_size. If the
% plot has too many data points, pdfTeX's buffer size may be exceeded.
% As a work-around, split the xData, yData into several chunks of data
% for each of which an \addplot will be generated.
% Get the length of the data array and the corresponding chung size
%TODO: scale `maxChunkLength` with the number of columns in the data array
len = size(data, 1);
chunkLength = m2t.args.maxChunkLength;
chunks = chunkLength * ones(ceil(len/chunkLength), 1);
if mod(len, chunkLength) ~=0
chunks(end) = mod(len, chunkLength);
end
% Cut the data into chunks
dataCell = mat2cell(data, chunks);
% Add an extra (overlap) point to the data stream otherwise the line
% between two data chunks would be broken. Technically, this is only
% needed when the plot has a line connecting the points, but the
% additional cost when there is no line doesn't justify the added
% complexity.
for i=1:length(dataCell)-1
dataCell{i}(end+1,:) = dataCell{i+1}(1,:);
end
end
% ==============================================================================
function [m2t, lineOpts] = getLineOptions(m2t, h)
% Gathers the line options.
lineOpts = opts_new();
% Get the options from the handle
lineWidth = get(h, 'LineWidth');
% Get the line style and check whether it is the default one
[lineStyle, isDefaultLS] = getAndCheckDefault('Line', h, 'LineStyle', '-');
if ~isDefaultLS && ~isNone(lineStyle) && (lineWidth > m2t.tol)
lineOpts = opts_add(lineOpts, translateLineStyle(lineStyle));
end
% Take over the line width in any case when in strict mode. If not, don't add
% anything in case of default line width and effectively take Pgfplots'
% default.
% Also apply the line width if no actual line is there; the markers make use
% of this, too.
matlabDefaultLineWidth = 0.5;
if ~isempty(m2t.semantic.LineWidth)
if ismember(lineWidth, [m2t.semantic.LineWidth{:,2}])
semStrID = lineWidth == [m2t.semantic.LineWidth{:,2}];
lineOpts = opts_add(lineOpts, m2t.semantic.LineWidth{semStrID,1});
else
warning('matlab2tikz:semanticLineWidthNotFound',...
['No semantic correspondance for lineWidth of ''%f'' found.'...
'Falling back to explicit export in points.'], lineWidth);
lineOpts = opts_add(lineOpts, 'line width', sprintf('%.1fpt', lineWidth));
end
elseif m2t.args.strict || ~abs(lineWidth-matlabDefaultLineWidth) <= m2t.tol
lineOpts = opts_add(lineOpts, 'line width', sprintf('%.1fpt', lineWidth));
end
% print no lines
if isNone(lineStyle) || lineWidth==0
lineOpts = opts_add(lineOpts, 'draw', 'none');
end
end
% ==============================================================================
function list = configureSemanticLineWidths(semanticLineWidths)
% Defines the default semantic options of pgfplots and updates it when applicable
if isnan(semanticLineWidths)
% Remove the list
list = {};
return;
end
% Pgf/TikZ defaults (see pgfmanual 3.0.1a section 15.3.1 / page 166)
list = {'ultra thin', 0.1;
'very thin', 0.2;
'thin', 0.4;
'semithick', 0.6;
'thick', 0.8;
'very thick', 1.2;
'ultra thick', 1.6 };
% Update defaults or append the user provided setting
for ii = 1:size(semanticLineWidths, 1)
% Check for redefinitions of defaults
[isOverride, idx] = ismember(semanticLineWidths{ii, 1}, list{:, 1})
if isOverride
list{idx, 2} = semanticLineWidths{ii, 2};
else
list{end+1} = semanticLineWidths{ii, :};
end
end
end
% ==============================================================================
function [m2t, drawOptions] = getMarkerOptions(m2t, h)
% Handles the marker properties of a line (or any other) plot.
drawOptions = opts_new();
marker = getOrDefault(h, 'Marker', 'none');
if ~isNone(marker)
markerSize = get(h, 'MarkerSize');
lineStyle = get(h, 'LineStyle');
lineWidth = get(h, 'LineWidth');
[tikzMarkerSize, isDefault] = ...
translateMarkerSize(m2t, marker, markerSize);
% take over the marker size in any case when in strict mode;
% if not, don't add anything in case of default marker size
% and effectively take Pgfplots' default.
if m2t.args.strict || ~isDefault
drawOptions = opts_add(drawOptions, 'mark size', ...
sprintf('%.1fpt', tikzMarkerSize));
end
markOptions = opts_new();
% make sure that the markers get painted in solid (and not dashed)
% if the 'lineStyle' is not solid (otherwise there is no problem)
if ~strcmpi(lineStyle, 'solid')
markOptions = opts_add(markOptions, 'solid');
end
% get the marker color right
markerInfo = getMarkerInfo(m2t, h, markOptions);
[m2t, markerInfo.options] = setColor(m2t, h, markerInfo.options, 'fill', markerInfo.FaceColor);
if ~strcmpi(markerInfo.EdgeColor,'auto')
[m2t, markerInfo.options] = setColor(m2t, h, markerInfo.options, '', markerInfo.EdgeColor);
else
if isprop(h,'EdgeColor')
color = get(h, 'EdgeColor');
else
color = get(h, 'Color');
end
[m2t, markerInfo.options] = setColor(m2t, h, markerInfo.options, '', color);
end
% add it all to drawOptions
drawOptions = opts_add(drawOptions, 'mark', markerInfo.tikz);
if ~isempty(markOptions)
drawOptions = opts_addSubOpts(drawOptions, 'mark options', ...
markerInfo.options);
end
end
end
% ==============================================================================
function [tikzMarkerSize, isDefault] = ...
translateMarkerSize(m2t, matlabMarker, matlabMarkerSize)
% The markersizes of Matlab and TikZ are related, but not equal. This
% is because
%
% 1.) MATLAB uses the MarkerSize property to describe something like
% the diameter of the mark, while TikZ refers to the 'radius',
% 2.) MATLAB and TikZ take different measures (e.g. the
% edge of a square vs. its diagonal).
if(~ischar(matlabMarker))
error('matlab2tikz:translateMarkerSize', ...
'Variable matlabMarker is not a string.');
end
if(~isnumeric(matlabMarkerSize))
error('matlab2tikz:translateMarkerSize', ...
'Variable matlabMarkerSize is not a numeral.');
end
% 6pt is the default MATLAB marker size for all markers
defaultMatlabMarkerSize = 6;
isDefault = abs(matlabMarkerSize(1)-defaultMatlabMarkerSize)<m2t.tol;
% matlabMarkerSize can be vector data, use first index to check the default
% marker size. When the script also handles different markers together with
% changing size and color, the test should be extended to a vector norm, e.g.
% sqrt(e^T*e) < tol, where e=matlabMarkerSize-defaultMatlabMarkerSize
switch (matlabMarker)
case 'none'
tikzMarkerSize = [];
case {'+','o','x','*','p','pentagram','h','hexagram'}
% In MATLAB, the marker size refers to the edge length of a
% square (for example) (~diameter), whereas in TikZ the
% distance of an edge to the center is the measure (~radius).
% Hence divide by 2.
tikzMarkerSize = matlabMarkerSize(:) / 2;
case '.'
% as documented on the Matlab help pages:
%
% Note that MATLAB draws the point marker (specified by the '.'
% symbol) at one-third the specified size.
% The point (.) marker type does not change size when the
% specified value is less than 5.
%
tikzMarkerSize = matlabMarkerSize(:) / 2 / 3;
case {'s','square'}
% Matlab measures the diameter, TikZ half the edge length
tikzMarkerSize = matlabMarkerSize(:) / 2 / sqrt(2);
case {'d','diamond'}
% MATLAB measures the width, TikZ the height of the diamond;
% the acute angle (at the top and the bottom of the diamond)
% is a manually measured 75 degrees (in TikZ, and MATLAB
% probably very similar); use this as a base for calculations
tikzMarkerSize = matlabMarkerSize(:) / 2 / atan(75/2 *pi/180);
case {'^','v','<','>'}
% for triangles, matlab takes the height
% and tikz the circumcircle radius;
% the triangles are always equiangular
tikzMarkerSize = matlabMarkerSize(:) / 2 * (2/3);
otherwise
error('matlab2tikz:translateMarkerSize', ...
'Unknown matlabMarker ''%s''.', matlabMarker);
end
end
% ==============================================================================
function [tikzMarker, markOptions] = ...
translateMarker(m2t, matlabMarker, markOptions, faceColorToggle)
% Translates MATLAB markers to their Tikz equivalents
% #COMPLEX: inherently large switch-case
if ~ischar(matlabMarker)
error('matlab2tikz:translateMarker:MarkerNotAString',...
'matlabMarker is not a string.');
end
switch (matlabMarker)
case 'none'
tikzMarker = '';
case '+'
tikzMarker = '+';
case 'o'
if faceColorToggle
tikzMarker = '*';
else
tikzMarker = 'o';
end
case '.'
tikzMarker = '*';
case 'x'
tikzMarker = 'x';
otherwise % the following markers are only available with PGF's
% plotmarks library
signalDependency(m2t, 'tikzlibrary', 'plotmarks');
hasFilledVariant = true;
switch (matlabMarker)
case '*'
tikzMarker = 'asterisk';
hasFilledVariant = false;
case {'s','square'}
tikzMarker = 'square';
case {'d','diamond'}
tikzMarker = 'diamond';
case '^'
tikzMarker = 'triangle';
case 'v'
tikzMarker = 'triangle';
markOptions = opts_add(markOptions, 'rotate', '180');
case '<'
tikzMarker = 'triangle';
markOptions = opts_add(markOptions, 'rotate', '90');
case '>'
tikzMarker = 'triangle';
markOptions = opts_add(markOptions, 'rotate', '270');
case {'p','pentagram'}
tikzMarker = 'star';
case {'h','hexagram'}
userWarning(m2t, 'MATLAB''s marker ''hexagram'' not available in TikZ. Replacing by ''star''.');
tikzMarker = 'star';
otherwise
error('matlab2tikz:translateMarker:unknownMatlabMarker',...
'Unknown matlabMarker ''%s''.',matlabMarker);
end
if faceColorToggle && hasFilledVariant
tikzMarker = [tikzMarker '*'];
end
end
end
% ==============================================================================
function [m2t, str] = drawPatch(m2t, handle)
% Draws a 'patch' graphics object (as found in contourf plots, for example).
%
str = '';
if ~isVisible(handle)
return
end
% This is for a quirky workaround for stacked bar plots.
m2t.axes{end}.nonbarPlotsPresent = true;
% Each row of the faces matrix represents a distinct patch
% NOTE: pgfplot uses zero-based indexing into vertices and interpolates
% counter-clockwise
Faces = get(handle,'Faces')-1;
Vertices = get(handle,'Vertices');
% 3D vs 2D
is3D = m2t.axes{end}.is3D;
if is3D
columnNames = {'x', 'y', 'z'};
plotCmd = 'addplot3';
Vertices = applyHgTransform(m2t, Vertices);
else
columnNames = {'x', 'y'};
plotCmd = 'addplot';
Vertices = Vertices(:,1:2);
end
% Process fill, edge colors and shader
[m2t,patchOptions, s] = shaderOpts(m2t,handle,'patch');
% Return empty axes if no face or edge colors
if isNone(s.plotType)
return
end
% -----------------------------------------------------------------------
% gather the draw options
% Make sure that legends are shown in area mode.
drawOptions = opts_add(opts_new,'area legend');
verticesTableOptions = opts_new();
% Marker options
[m2t, markerOptions] = getMarkerOptions(m2t, handle);
drawOptions = opts_merge(drawOptions, markerOptions);
% Line options
[m2t, lineOptions] = getLineOptions(m2t, handle);
drawOptions = opts_merge(drawOptions, lineOptions);
% If the line is not visible, set edgeColor to none. Otherwise pgfplots
% draws it by default
if ~isLineVisible(handle)
s.edgeColor = 'none';
end
% No patch: if one patch and single face/edge color
isFaceColorFlat = isempty(strfind(opts_get(patchOptions, 'shader'),'interp'));
if size(Faces,1) == 1 && s.hasOneEdgeColor && isFaceColorFlat
ptType = '';
cycle = conditionallyCyclePath(Vertices);
[m2t, drawOptions] = setColor(m2t, handle, drawOptions, 'draw', ...
s.edgeColor, 'none');
[m2t, drawOptions] = setColor(m2t, handle, drawOptions, 'fill', ...
s.faceColor);
[drawOptions] = opts_copy(patchOptions, 'draw opacity', drawOptions);
[drawOptions] = opts_copy(patchOptions, 'fill opacity', drawOptions);
else % Multiple patches
% Patch table type
ptType = 'patch table';
cycle = '';
drawOptions = opts_add(drawOptions,'table/row sep','crcr');
% TODO: is the above "crcr" compatible with pgfplots 1.12 ?
% TODO: is a "patch table" externalizable?
% Enforce 'patch' or cannot use 'patch table='
if strcmpi(s.plotType,'mesh')
drawOptions = opts_add(drawOptions,'patch');
end
drawOptions = opts_add(drawOptions,s.plotType); % Eventually add mesh, but after patch!
drawOptions = getPatchShape(m2t, handle, drawOptions, patchOptions);
[m2t, drawOptions, Vertices, Faces, verticesTableOptions, ptType, ...
columnNames] = setColorsOfPatches(m2t, handle, drawOptions, ...
Vertices, Faces, verticesTableOptions, ptType, columnNames, ...
isFaceColorFlat, s);
end
drawOptions = maybeShowInLegend(m2t.currentHandleHasLegend, drawOptions);
m2t = jumpAtUnboundCoords(m2t, Faces(:));
% Add Faces table
if ~isempty(ptType)
[m2t, facesTable] = makeTable(m2t, repmat({''},1,size(Faces,2)), Faces);
drawOptions = opts_add(drawOptions, ptType, sprintf('{%s}', facesTable));
end
% Plot the actual data.
[m2t, verticesTable, tableOptions] = makeTable(m2t, columnNames, Vertices);
tableOptions = opts_merge(tableOptions, verticesTableOptions);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\n\\%s[%s]\ntable[%s] {%s}%s;\n',...
plotCmd, drawOpts, tabOpts, verticesTable, cycle);
end
% ==============================================================================
function [m2t, drawOptions, Vertices, Faces, verticesTableOptions, ptType, ...
columnNames] = setColorsOfPatches(m2t, handle, drawOptions, ...
Vertices, Faces, verticesTableOptions, ptType, columnNames, isFaceColorFlat, s)
% this behemoth does the color setting for patches
% TODO: this function can probably be split further, just look at all those
% parameters being passed.
fvCData = get(handle,'FaceVertexCData');
rowsCData = size(fvCData,1);
% We have CData for either all faces or vertices
if rowsCData > 1
% Add the color map
m2t = m2t_addAxisOption(m2t, matlab2pgfplotsColormap(m2t, m2t.current.colormap));
% Determine if mapping is direct or scaled
CDataMapping = get(handle,'CDataMapping');
if strcmpi(CDataMapping, 'direct')
drawOptions = opts_add(drawOptions, 'colormap access','direct');
end
% Switch to face CData if not using interpolated shader
isVerticesCData = rowsCData == size(Vertices,1);
if isFaceColorFlat && isVerticesCData
% Take first vertex color (see FaceColor in Patch Properties)
fvCData = fvCData(Faces(:,1)+ 1,:);
rowsCData = size(fvCData,1);
isVerticesCData = false;
end
% Point meta as true color CData, i.e. RGB in [0,1]
if size(fvCData,2) == 3
% Create additional custom colormap
m2t.axes{end}.options(end+1,:) = ...
{matlab2pgfplotsColormap(m2t, fvCData, 'patchmap'), []};
drawOptions = opts_append(drawOptions, 'colormap name','patchmap');
% Index into custom colormap
fvCData = (0:rowsCData-1)';
end
% Add pointmeta data to vertices or faces
if isVerticesCData
columnNames{end+1} = 'c';
verticesTableOptions = opts_add(verticesTableOptions, 'point meta','\thisrow{c}');
Vertices = [Vertices, fvCData];
else
ptType = 'patch table with point meta';
Faces = [Faces fvCData];
end
else
% Scalar FaceVertexCData, i.e. one color mapping for all patches,
% used e.g. by Octave in drawing barseries
[m2t,xFaceColor] = getColor(m2t, handle, s.faceColor, 'patch');
drawOptions = opts_add(drawOptions, 'fill', xFaceColor);
end
end
% ==============================================================================
function [drawOptions] = maybeShowInLegend(showInLegend, drawOptions)
% sets the appropriate options to show/hide the plot in the legend
if ~showInLegend
% No legend entry found. Don't include plot in legend.
drawOptions = opts_add(drawOptions, 'forget plot');
end
end
% ==============================================================================
function [m2t, options] = setColor(m2t, handle, options, property, color, noneValue)
% assigns the MATLAB color of the object identified by "handle" to the LaTeX
% property stored in the options array. An optional "noneValue" can be provided
% that is set when the color == 'none' (if it is omitted, the property will not
% be set).
% TODO: probably this should be integrated with getAndCheckDefault etc.
if opts_has(options,property) && isNone(opts_get(options,property))
return
end
if ~isNone(color)
[m2t, xcolor] = getColor(m2t, handle, color, 'patch');
if ~isempty(xcolor)
% this may happen when color == 'flat' and CData is Nx3, e.g. in
% scatter plot or in patches
if isempty(property)
options = opts_add(options, xcolor);
else
options = opts_add(options, property, xcolor);
end
end
else
if exist('noneValue','var')
options = opts_add(options, property, noneValue);
end
end
end
% ==============================================================================
function drawOptions = getPatchShape(m2t, h, drawOptions, patchOptions)
% Retrieves the shape options (i.e. number of vertices) of patch objects
% Depending on the number of vertices, patches can be triangular, rectangular
% or polygonal
% See pgfplots 1.12 manual section 5.8.1 "Additional Patch Types" and the
% patchplots library
vertexCount = size(get(h, 'Faces'), 2);
switch vertexCount
case 3 % triangle (default)
% do nothing special
case 4 % rectangle
drawOptions = opts_add(drawOptions,'patch type', 'rectangle');
otherwise % generic polygon
userInfo(m2t, '\nMake sure to load \\usepgfplotslibrary{patchplots} in the preamble.\n');
% Default interpolated shader,not supported by polygon, to faceted
isFaceColorFlat = isempty(strfind(opts_get(patchOptions, 'shader'),'interp'));
if ~isFaceColorFlat
% NOTE: check if pgfplots supports this (or specify version)
userInfo(m2t, '\nPgfplots does not support interpolation for polygons.\n Use patches with at most 4 vertices.\n');
patchOptions = opts_remove(patchOptions, 'shader');
patchOptions = opts_add(patchOptions, 'shader', 'faceted');
end
% Add draw options
drawOptions = opts_add(drawOptions, 'patch type', 'polygon');
drawOptions = opts_add(drawOptions, 'vertex count', ...
sprintf('%d', vertexCount));
end
drawOptions = opts_merge(drawOptions, patchOptions);
end
% ==============================================================================
function [cycle] = conditionallyCyclePath(data)
% returns "--cycle" when the path should be cyclic in pgfplots
% Mostly, this is the case UNLESS the data record starts or ends with a NaN
% record (i.e. a break in the path)
if any(~isfinite(data([1 end],:)))
cycle = '';
else
cycle = '--cycle';
end
end
% ==============================================================================
function m2t = jumpAtUnboundCoords(m2t, data)
% signals the axis to allow discontinuities in the plot at unbounded
% coordinates (i.e. Inf and NaN).
% See also pgfplots 1.12 manual section 4.5.13 "Interrupted Plots".
if any(~isfinite(data(:)))
m2t = needsPgfplotsVersion(m2t, [1 4]);
m2t = m2t_addAxisOption(m2t, 'unbounded coords', 'jump');
end
end
% ==============================================================================
function [m2t, str] = drawImage(m2t, handle)
str = '';
if ~isVisible(handle)
return
end
% read x-, y-, and color-data
xData = get(handle, 'XData');
yData = get(handle, 'YData');
cData = get(handle, 'CData');
if (m2t.args.imagesAsPng)
[m2t, str] = imageAsPNG(m2t, handle, xData, yData, cData);
else
[m2t, str] = imageAsTikZ(m2t, handle, xData, yData, cData);
end
% Make sure that the axes are still visible above the image.
m2t = m2t_addAxisOption(m2t, 'axis on top');
end
% ==============================================================================
function [m2t, str] = imageAsPNG(m2t, handle, xData, yData, cData)
[m2t, fileNum] = incrementGlobalCounter(m2t, 'pngFile');
% ------------------------------------------------------------------------
% draw a png image
[pngFileName, pngReferencePath] = externalFilename(m2t, fileNum, '.png');
% Get color indices for indexed images and truecolor values otherwise
if ndims(cData) == 2 %#ok don't use ismatrix (cfr. #143)
[m2t, colorData] = cdata2colorindex(m2t, cData, handle);
else
colorData = cData;
end
m = size(cData, 1);
n = size(cData, 2);
alphaData = normalizedAlphaValues(m2t, get(handle,'AlphaData'), handle);
if numel(alphaData) == 1
alphaData = alphaData(ones(size(colorData(:,:,1))));
end
[colorData, alphaData] = flipImageIfAxesReversed(m2t, colorData, alphaData);
% Write an indexed or a truecolor image
hasAlpha = true;
if isfloat(alphaData) && all(alphaData(:) == 1)
alphaOpts = {};
hasAlpha = false;
else
alphaOpts = {'Alpha', alphaData};
end
if (ndims(colorData) == 2) %#ok don't use ismatrix (cfr. #143)
if size(m2t.current.colormap, 1) <= 256 && ~hasAlpha
% imwrite supports maximum 256 values in a colormap (i.e. 8 bit)
% and no alpha channel for indexed PNG images.
imwrite(colorData, m2t.current.colormap, ...
pngFileName, 'png');
else % use true-color instead
imwrite(ind2rgb(colorData, m2t.current.colormap), ...
pngFileName, 'png', alphaOpts{:});
end
else
imwrite(colorData, pngFileName, 'png', alphaOpts{:});
end
% -----------------------------------------------------------------------
% dimensions of a pixel in axes units
if n == 1
xLim = get(m2t.current.gca, 'XLim');
xw = xLim(2) - xLim(1);
else
xw = (xData(end)-xData(1)) / (n-1);
end
if m == 1
yLim = get(m2t.current.gca, 'YLim');
yw = yLim(2) - yLim(1);
else
yw = (yData(end)-yData(1)) / (m-1);
end
opts = opts_new();
opts = opts_add(opts, 'xmin', sprintf(m2t.ff, xData(1 ) - xw/2));
opts = opts_add(opts, 'xmax', sprintf(m2t.ff, xData(end) + xw/2));
opts = opts_add(opts, 'ymin', sprintf(m2t.ff, yData(1 ) - yw/2));
opts = opts_add(opts, 'ymax', sprintf(m2t.ff, yData(end) + yw/2));
% Print out
drawOpts = opts_print(opts);
str = sprintf('\\addplot [forget plot] graphics [%s] {%s};\n', ...
drawOpts, pngReferencePath);
userInfo(m2t, ...
['\nA PNG file is stored at ''%s'' for which\n', ...
'the TikZ file contains a reference to ''%s''.\n', ...
'You may need to adapt this, depending on the relative\n', ...
'locations of the master TeX file and the included TikZ file.\n'], ...
pngFileName, pngReferencePath);
end
% ==============================================================================
function [m2t, str] = imageAsTikZ(m2t, handle, xData, yData, cData)
% writes an image as raw TikZ commands (STRONGLY DISCOURAGED)
% set up cData
if ndims(cData) == 3
cData = cData(end:-1:1,:,:);
else
cData = cData(end:-1:1,:);
end
% Generate uniformly distributed X, Y, although xData and yData may be
% non-uniform.
% This is MATLAB(R) behavior.
[X, hX] = constructUniformXYDataForImage(xData, size(cData, 2));
[Y, hY] = constructUniformXYDataForImage(yData, size(cData, 1));
[m2t, xcolor] = getColor(m2t, handle, cData, 'image');
% The following section takes pretty long to execute, although in
% principle it is discouraged to use TikZ for those; LaTeX will take
% forever to compile.
% Still, a bug has been filed on MathWorks to allow for one-line
% sprintf'ing with (string+num) cells (Request ID: 1-9WHK4W);
% <http://www.mathworks.de/support/service_requests/Service_Request_Detail.do?ID=183481&filter=&sort=&statusorder=0&dateorder=0>.
% An alternative approach could be to use 'surf' or 'patch' of pgfplots
% with inline tables.
str = '';
m = length(X);
n = length(Y);
imageString = cell(1, m);
for i = 1:m
subString = cell(1, n);
for j = 1:n
subString{j} = sprintf(['\t\\fill [%s] ', ...
'(axis cs:', m2t.ff,',', m2t.ff,') rectangle ', ...
'(axis cs:', m2t.ff,',',m2t.ff,');\n'], ...
xcolor{n-j+1,i}, ...
X(i)-hX/2, Y(j)-hY/2, ...
X(i)+hX/2, Y(j)+hY/2);
end
imageString{i} = join(m2t, subString, '');
end
str = join(m2t, [str, imageString], '');
end
function [XY, delta] = constructUniformXYDataForImage(XYData, expectedLength)
% Generate uniformly distributed X, Y, although xData/yData may be
% non-uniform. Dimension indicates the corresponding dimension in the cData matrix.
switch length(XYData)
case 2 % only the limits given; common for generic image plots
delta = 1;
case expectedLength % specific x/y-data is given
delta = (XYData(end)-XYData(1)) / (length(XYData)-1);
otherwise
error('drawImage:arrayLengthMismatch', ...
'CData length (%d) does not match X/YData length (%d).', ...
expectedLength, length(XYData));
end
XY = XYData(1):delta:XYData(end);
end
% ==============================================================================
function [colorData, alphaData] = flipImageIfAxesReversed(m2t, colorData, alphaData)
% flip the image if reversed
if m2t.xAxisReversed
colorData = colorData(:, end:-1:1, :);
alphaData = alphaData(:, end:-1:1);
end
if ~m2t.yAxisReversed % y-axis direction is reversed normally for images, flip otherwise
colorData = colorData(end:-1:1, :, :);
alphaData = alphaData(end:-1:1, :);
end
end
% ==============================================================================
function alpha = normalizedAlphaValues(m2t, alpha, handle)
alphaDataMapping = getOrDefault(handle, 'AlphaDataMapping', 'none');
switch lower(alphaDataMapping)
case 'none' % no rescaling needed
case 'scaled'
ALim = get(m2t.current.gca, 'ALim');
AMax = ALim(2);
AMin = ALim(1);
if ~isfinite(AMax)
AMax = max(alpha(:)); %NOTE: is this right?
end
alpha = (alpha - AMin)./(AMax - AMin);
case 'direct'
alpha = ind2rgb(alpha, get(m2t.current.gcf, 'Alphamap'));
otherwise
error('matlab2tikz:UnknownAlphaMapping', ...
'Unknown alpha mapping "%s"', alphaMapping);
end
if isfloat(alpha) %important, alpha data can have integer type which should not be scaled
alpha = min(1,max(alpha,0)); % clip at range [0, 1]
end
end
% ==============================================================================
function [m2t, str] = drawContour(m2t, h)
if isHG2()
[m2t, str] = drawContourHG2(m2t, h);
else
% Save legend state for the contour group
hasLegend = m2t.currentHandleHasLegend;
% Plot children patches
children = allchild(h);
N = numel(children);
str = cell(N,1);
for ii = 1:N
% Plot in reverse order
child = children(N-ii+1);
isContourLabel = strcmpi(get(child,'type'),'text');
if isContourLabel
[m2t, str{ii}] = drawText(m2t,child);
else
[m2t, str{ii}] = drawPatch(m2t,child);
end
% Only first child can be in the legend
m2t.currentHandleHasLegend = false;
end
str = strcat(str,sprintf('\n'));
str = [str{:}];
% Restore group's legend state
m2t.currentHandleHasLegend = hasLegend;
end
end
% ==============================================================================
function [m2t, str] = drawContourHG2(m2t, h)
str = '';
if ~isVisible(h)
return
end
% Retrieve ContourMatrix
contours = get(h,'ContourMatrix')';
[istart, nrows] = findStartOfContourData(contours);
% Scale negative contours one level down (for proper coloring)
Levels = contours(istart,1);
LevelList = get(h,'LevelList');
ineg = Levels < 0;
if any(ineg) && min(LevelList) < min(Levels)
[idx,pos] = ismember(Levels, LevelList);
idx = idx & ineg;
contours(istart(idx)) = LevelList(pos(idx)-1);
end
% Draw a contour group (MATLAB R2014b and newer only)
isFilled = isOn(get(h,'Fill'));
if isFilled
[m2t, str] = drawFilledContours(m2t, h, contours, istart, nrows);
else
% Add colormap
cmap = m2t.current.colormap;
m2t = m2t_addAxisOption(m2t, matlab2pgfplotsColormap(m2t, cmap));
% Contour table in Matlab format
plotOptions = opts_new();
plotOptions = opts_add(plotOptions,'contour prepared');
plotOptions = opts_add(plotOptions,'contour prepared format','matlab');
% Labels
if isOff(get(h,'ShowText'))
plotOptions = opts_add(plotOptions,'contour/labels','false');
end
% Get line properties
[m2t, lineOptions] = getLineOptions(m2t, h);
% Check for special color settings
[lineColor, isDefaultColor] = getAndCheckDefault('contour', h, 'LineColor', 'flat');
if ~isDefaultColor
[m2t, lineOptions] = setColor(m2t, h, lineOptions, 'contour/draw color', lineColor, 'none');
end
% Merge the line options with the contour plot options
plotOptions = opts_merge(plotOptions, lineOptions);
% Make contour table
[m2t, table, tableOptions] = makeTable(m2t, {'',''}, contours);
% Print out
plotOpts = opts_print(plotOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s] {%%\n%s};\n', ...
plotOpts, tabOpts, table);
end
end
% ==============================================================================
function [istart, nrows] = findStartOfContourData(contours)
% Index beginning of contour data (see contourc.m for details)
nrows = size(contours,1);
istart = false(nrows,1);
pos = 1;
while pos < nrows
istart(pos) = true;
pos = pos + contours(pos, 2) + 1;
end
istart = find(istart);
end
% ==============================================================================
function [m2t, str] = drawFilledContours(m2t, h, contours, istart, nrows)
% Loop each contour and plot a filled region
%
% NOTE:
% - we cannot plot from inner to outer contour since the last
% filled area will cover the inner regions. Therefore, we need to
% invert the plotting order in those cases.
% - we need to distinguish between contour groups. A group is
% defined by inclusion, i.e. its members are contained within one
% outer contour. The outer contours of two groups cannot include
% each other.
str = '';
if ~isVisible(h)
return
end
% Split contours in cell array
cellcont = mat2cell(contours, diff([istart; nrows+1]));
ncont = numel(cellcont);
% Determine contour groups and the plotting order.
% The ContourMatrix lists the contours in ascending order by level.
% Hence, if the lowest (first) contour contains any others, then the
% group will be a peak. Otherwise, the group will be a valley, and
% the contours will have to be plotted in reverse order, i.e. from
% highest (largest) to lowest (narrowest).
%FIXME: close the contours over the border of the domain, see #723.
order = NaN(ncont,1);
ifree = true(ncont,1);
from = 1;
while any(ifree)
% Select peer with lowest level among the free contours, i.e.
% those which do not belong to any group yet
pospeer = find(ifree,1,'first');
peer = cellcont{pospeer};
igroup = false(ncont,1);
% Loop through all contours
for ii = 1:numel(cellcont)
if ~ifree(ii), continue, end
curr = cellcont{ii};
% Current contour contained in the peer
if inpolygon(curr(2,1),curr(2,2), peer(2:end,1),peer(2:end,2))
igroup(ii) = true;
isinverse = false;
% Peer contained in the current
elseif inpolygon(peer(2,1),peer(2,2),curr(2:end,1),curr(2:end,2))
igroup(ii) = true;
isinverse = true;
end
end
% Order members of group according to the inclusion principle
nmembers = nnz(igroup ~= 0);
if isinverse
order(igroup) = nmembers+from-1:-1:from;
else
order(igroup) = from:nmembers+from-1;
end
% Continue numbering
from = from + nmembers;
ifree = ifree & ~igroup;
end
% Reorder the contours
cellcont(order,1) = cellcont;
% Add zero level fill
xdata = get(h,'XData');
ydata = get(h,'YData');
%FIXME: determine the contour at the zero level not just its bounding box
% See also: #721
zerolevel = [0, 4;
min(xdata(:)), min(ydata(:));
min(xdata(:)), max(ydata(:));
max(xdata(:)), max(ydata(:));
max(xdata(:)), min(ydata(:))];
cellcont = [zerolevel; cellcont];
% Plot
columnNames = {'x','y'};
for ii = 1:ncont + 1
drawOptions = opts_new();
% Get fill color
zval = cellcont{ii}(1,1);
[m2t, xcolor] = getColor(m2t,h,zval,'image');
drawOptions = opts_add(drawOptions,'fill',xcolor);
% Get line properties
lineColor = get(h, 'LineColor');
[m2t, drawOptions] = setColor(m2t, h, drawOptions, 'draw', lineColor, 'none');
[m2t, lineOptions] = getLineOptions(m2t, h);
drawOptions = opts_merge(drawOptions, lineOptions);
% Toggle legend entry
hasLegend = ii == 1 && m2t.currentHandleHasLegend;
drawOptions = maybeShowInLegend(hasLegend, drawOptions);
% Print table
[m2t, table, tableOptions] = makeTable(m2t, columnNames, cellcont{ii}(2:end,:));
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('%s\\addplot[%s] table[%s] {%%\n%s};\n', ...
str, drawOpts, tabOpts, table);
end
end
% ==============================================================================
function [m2t, str] = drawHggroup(m2t, h)
% Continue according to the plot type. Since the function `handle` is
% not available in Octave, the plot type will be guessed or the fallback type
% 'unknown' used.
% #COMPLEX: big switch-case
switch getEnvironment()
case 'MATLAB'
cl = class(handle(h));
case 'Octave'
% Function `handle` is not yet implemented in Octave
% Consequently the plot type needs to be guessed. See #645.
cl = guessOctavePlotType(h);
otherwise
errorUnknownEnvironment();
end
switch(cl)
case {'specgraph.barseries', 'matlab.graphics.chart.primitive.Bar'}
% hist plots and friends
[m2t, str] = drawBarseries(m2t, h);
case {'specgraph.stemseries', 'matlab.graphics.chart.primitive.Stem'}
% stem plots
[m2t, str] = drawStemSeries(m2t, h);
case {'specgraph.stairseries', 'matlab.graphics.chart.primitive.Stair'}
% stair plots
[m2t, str] = drawStairSeries(m2t, h);
case {'specgraph.areaseries', 'matlab.graphics.chart.primitive.Area'}
% scatter plots
[m2t,str] = drawAreaSeries(m2t, h);
case {'specgraph.quivergroup', 'matlab.graphics.chart.primitive.Quiver'}
% quiver arrows
[m2t, str] = drawQuiverGroup(m2t, h);
case {'specgraph.errorbarseries', 'matlab.graphics.chart.primitive.ErrorBar'}
% error bars
[m2t,str] = drawErrorBars(m2t, h);
case {'specgraph.scattergroup','matlab.graphics.chart.primitive.Scatter'}
% scatter plots
[m2t,str] = drawScatterPlot(m2t, h);
case {'specgraph.contourgroup', 'matlab.graphics.chart.primitive.Contour'}
[m2t,str] = drawContour(m2t, h);
case {'hggroup', 'matlab.graphics.primitive.Group'}
% handle all those the usual way
[m2t, str] = handleAllChildren(m2t, h);
case 'unknown'
% Octave only: plot type could not be determined
% Fall back to basic plotting
[m2t, str] = handleAllChildren(m2t, h);
otherwise
userWarning(m2t, 'Don''t know class ''%s''. Default handling.', cl);
try
m2tBackup = m2t;
[m2t, str] = handleAllChildren(m2t, h);
catch ME
userWarning(m2t, 'Default handling for ''%s'' failed. Continuing as if it did not occur. \n Original Message:\n %s', cl, getReport(ME));
[m2t, str] = deal(m2tBackup, ''); % roll-back
end
end
end
% ==============================================================================
% Function `handle` is not yet implemented in Octave.
% Consequently the plot type needs to be guessed. See #645.
% If the type can not be determined reliably, 'unknown' will be set.
function cl = guessOctavePlotType(h)
% scatter plots
if hasProperties(h, {'marker','sizedata','cdata'}, {})
cl = 'specgraph.scattergroup';
% error bars
elseif hasProperties(h, {'udata','ldata'}, {})
cl = 'specgraph.errorbarseries';
% quiver plots
elseif hasProperties(h, {'udata','vdata'}, {'ldata'})
cl = 'specgraph.quivergroup';
% bar plots
elseif hasProperties(h, {'bargroup','barwidth', 'barlayout'}, {})
cl = 'specgraph.barseries';
% unknown plot type
else
cl = 'unknown';
end
end
% ==============================================================================
function bool = hasProperties(h, fieldsExpectedPresent, fieldsExpectedAbsent)
% Check if object has all of the given properties (case-insensitive).
% h handle to object (e.g. `gcf` or `gca`)
% fieldsExpectedPresent cell array of strings with property names to be present
% fieldsExpectedPresent cell array of strings with property names to be absent
fields = lower(fieldnames(get(h)));
present = all(ismember(lower(fieldsExpectedPresent), fields));
absent = ~any(ismember(lower(fieldsExpectedAbsent), fields));
bool = present && absent;
end
% ==============================================================================
function m2t = drawAnnotations(m2t)
% Draws annotation in Matlab (Octave not supported).
% In HG1 annotations are children of an invisible axis called scribeOverlay.
% In HG2 annotations are children of annotationPane object which does not
% have any axis properties. Hence, we cannot simply handle it with a
% drawAxes() call.
% Octave
if strcmpi(getEnvironment,'Octave')
return
end
% Get annotation handles
if isHG2
annotPanes = findall(m2t.current.gcf,'Tag','scribeOverlay');
children = allchild(annotPanes);
%TODO: is this dead code?
if iscell(children)
children = [children{:}];
end
annotHandles = findall(children,'Visible','on');
else
annotHandles = findall(m2t.scribeLayer,'-depth',1,'Visible','on');
end
% There are no anotations
if isempty(annotHandles)
return
end
% Create fake simplified axes overlay (no children)
warning('off', 'matlab2tikz:NoChildren')
scribeLayer = axes('Units','Normalized','Position',[0,0,1,1],'Visible','off');
m2t = drawAxes(m2t, scribeLayer);
warning('on', 'matlab2tikz:NoChildren')
% Plot in reverse to preserve z-ordering and assign the converted
% annotations to the converted fake overlay
for ii = numel(annotHandles):-1:1
m2t = drawAnnotationsHelper(m2t,annotHandles(ii));
end
% Delete fake overlay graphics object
delete(scribeLayer)
end
% ==============================================================================
function m2t = drawAnnotationsHelper(m2t,h)
% Get class name
try
cl = class(handle(h));
catch
cl = 'unknown';
end
switch cl
% Line
case {'scribe.line', 'matlab.graphics.shape.Line'}
[m2t, str] = drawLine(m2t, h);
% Ellipse
case {'scribe.scribeellipse','matlab.graphics.shape.Ellipse'}
[m2t, str] = drawEllipse(m2t, h);
% Arrows
case {'scribe.arrow', 'scribe.doublearrow'}%,...
%'matlab.graphics.shape.Arrow', 'matlab.graphics.shape.DoubleEndArrow'}
% Annotation: single and double Arrow, line
% TODO:
% - write a drawArrow(). Handle all info info directly
% without using handleAllChildren() since HG2 does not have
% children (so no shortcut).
% - It would be good if drawArrow() was callable on a
% matlab.graphics.shape.TextArrow object to draw the arrow
% part.
[m2t, str] = handleAllChildren(m2t, h);
% Text box
case {'scribe.textbox','matlab.graphics.shape.TextBox'}
[m2t, str] = drawText(m2t, h);
% Tetx arrow
case {'scribe.textarrow'}%,'matlab.graphics.shape.TextArrow'}
% TODO: rewrite drawTextarrow. Handle all info info directly
% without using handleAllChildren() since HG2 does not
% have children (so no shortcut) as used for
% scribe.textarrow.
[m2t, str] = drawTextarrow(m2t, h);
% Rectangle
case {'scribe.scriberect', 'matlab.graphics.shape.Rectangle'}
[m2t, str] = drawRectangle(m2t, h);
otherwise
userWarning(m2t, 'Don''t know annotation ''%s''.', cl);
return
end
% Add annotation to scribe overlay
m2t.axes{end} = addChildren(m2t.axes{end}, str);
end
% ==============================================================================
function [m2t,str] = drawSurface(m2t, h)
[m2t, opts, s] = shaderOpts(m2t, h,'surf');
tableOptions = opts_new();
% Allow for empty surf
if isNone(s.plotType)
str = '';
return
end
[dx, dy, dz, numrows] = getXYZDataFromSurface(h);
m2t = jumpAtUnboundCoords(m2t, [dx(:); dy(:); dz(:)]);
[m2t, opts] = addZBufferOptions(m2t, h, opts);
% Check if 3D
is3D = m2t.axes{end}.is3D;
if is3D
columnNames = {'x','y','z','c'};
plotCmd = 'addplot3';
data = applyHgTransform(m2t, [dx(:), dy(:), dz(:)]);
else
columnNames = {'x','y','c'};
plotCmd = 'addplot';
data = [dx(:), dy(:)];
end
% There are several possibilities of how colors are specified for surface
% plots:
% * explicitly by RGB-values,
% * implicitly through a color map with a point-meta coordinate,
% * implicitly through a color map with a given coordinate (e.g., z).
%
% Check if we need extra CData.
CData = get(h, 'CData');
if length(size(CData)) == 3 && size(CData, 3) == 3
% Create additional custom colormap
nrows = size(data,1);
CData = reshape(CData, nrows,3);
m2t.axes{end}.options(end+1,:) = ...
{matlab2pgfplotsColormap(m2t, CData, 'patchmap'), []};
% Index into custom colormap
color = (0:nrows-1)';
tableOptions = opts_add(tableOptions, 'colormap name','surfmap');
else
opts = opts_add(opts,matlab2pgfplotsColormap(m2t, m2t.current.colormap),'');
% If NaNs are present in the color specifications, don't use them for
% Pgfplots; they may be interpreted as strings there.
% Note:
% Pgfplots actually does a better job than MATLAB in determining what
% colors to use for the patches. The circular test case on
% http://www.mathworks.de/de/help/matlab/ref/pcolor.html, for example
% yields a symmetric setup in Pgfplots (and doesn't in MATLAB).
needsPointmeta = any(xor(isnan(dz(:)), isnan(CData(:)))) ...
|| any(abs(CData(:) - dz(:)) > 1.0e-10);
if needsPointmeta
color = CData(:);
else
color = dz(:); % Fallback on the z-values, especially if 2D view
end
end
tableOptions = opts_add(tableOptions, 'point meta','\thisrow{c}');
data = [data, color];
% Add mesh/rows=<num rows> for specifying the row data instead of empty
% lines in the data list below. This makes it possible to reduce the
% data writing to one single sprintf() call.
opts = opts_add(opts,'mesh/rows',sprintf('%d', numrows));
% Print the addplot options
str = sprintf('\n\\%s[%%\n%s,\n%s]', plotCmd, s.plotType, opts_print(opts));
% Print the data
[m2t, table, tabOptsExtra] = makeTable(m2t, columnNames, data);
tableOptions = opts_merge(tabOptsExtra, tableOptions);
tabOpts = opts_print(tableOptions);
% Here is where everything is put together
str = sprintf('%s\ntable[%s] {%%\n%s};\n', ...
str, tabOpts, table);
% TODO:
% - remove grids in spectrogram by either removing grid command
% or adding: 'grid=none' from/in axis options
% - handling of huge data amounts in LaTeX.
[m2t, labelString] = addLabel(m2t, h);
str = [str, labelString];
end
% ==============================================================================
function [m2t, opts] = addZBufferOptions(m2t, h, opts)
% Enforce 'z buffer=sort' if shader is flat and is a 3D plot. It is to
% avoid overlapping e.g. sphere plots and to properly mimic Matlab's
% coloring of faces.
% NOTE:
% - 'z buffer=sort' is computationally more expensive for LaTeX, we
% could try to avoid it in some default situations, e.g. when dx and
% dy are rank-1-matrices.
% - hist3D plots should not be z-sorted or the highest bars will cover
% the shortest one even if positioned in the back
isShaderFlat = isempty(strfind(opts_get(opts, 'shader'), 'interp'));
isHist3D = strcmpi(get(h,'tag'), 'hist3');
is3D = m2t.axes{end}.is3D;
if is3D && isShaderFlat && ~isHist3D
opts = opts_add(opts, 'z buffer', 'sort');
% Pgfplots 1.12 contains a bug fix that fixes legend entries when
% 'z buffer=sort' has been set. So, it's easier to always require that
% version anyway. See #504 for more information.
m2t = needsPgfplotsVersion(m2t, [1,12]);
end
end
% ==============================================================================
function [dx, dy, dz, numrows] = getXYZDataFromSurface(h)
% retrieves X, Y and Z data from a Surface plot. The data gets returned in a
% wastefull format where the dimensions of these data vectors is equal, akin
% to the format used by meshgrid.
dx = get(h, 'XData');
dy = get(h, 'YData');
dz = get(h, 'ZData');
[numcols, numrows] = size(dz);
% If dx or dy are given as vectors, convert them to the (wasteful) matrix
% representation first. This makes sure we can treat the data with one
% single sprintf() command below.
if isvector(dx)
dx = ones(numcols,1) * dx(:)';
end
if isvector(dy)
dy = dy(:) * ones(1,numrows);
end
end
% ==============================================================================
function [m2t, str] = drawVisibleText(m2t, handle)
% Wrapper for drawText() that only draws visible text
% There may be some text objects floating around a MATLAB figure which are
% handled by other subfunctions (labels etc.) or don't need to be handled at
% all.
% The HandleVisibility says something about whether the text handle is
% visible as a data structure or not. Typically, a handle is hidden if the
% graphics aren't supposed to be altered, e.g., axis labels. Most of those
% entities are captured by matlab2tikz one way or another, but sometimes they
% are not. This is the case, for example, with polar plots and the axis
% descriptions therein. Also, Matlab treats text objects with a NaN in the
% position as invisible.
if any(isnan(get(handle, 'Position')) | isnan(get(handle, 'Rotation'))) ...
|| isOff(get(handle, 'Visible')) ...
|| (isOff(get(handle, 'HandleVisibility')) && ...
~m2t.args.showHiddenStrings)
str = '';
return;
end
[m2t, str] = drawText(m2t, handle);
end
% ==============================================================================
function [m2t, str] = drawText(m2t, handle)
% Adding text node anywhere in the axes environment.
% Not that, in Pgfplots, long texts get cut off at the axes. This is
% Different from the default MATLAB behavior. To fix this, one could use
% /pgfplots/after end axis/.code.
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% get required properties
content = get(handle, 'String');
Interpreter = get(handle, 'Interpreter');
content = prettyPrint(m2t, content, Interpreter);
% Concatenate multiple lines
content = join(m2t, content, '\\');
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% translate them to pgf style
style = opts_new();
bgColor = get(handle,'BackgroundColor');
[m2t, style] = setColor(m2t, handle, style, 'fill', bgColor);
style = getXYAlignmentOfText(handle, style);
style = getRotationOfText(m2t, handle, style);
[m2t, fontStyle] = getFontStyle(m2t, handle);
style = opts_merge(style, fontStyle);
EdgeColor = get(handle, 'EdgeColor');
[m2t, style] = setColor(m2t, handle, style, 'draw', EdgeColor);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% plot the thing
[m2t, posString] = getPositionOfText(m2t, handle);
styleOpts = opts_print(style);
str = sprintf('\\node[%s]\nat %s {%s};\n', ...
styleOpts, posString, content);
end
% ==============================================================================
function [style] = getXYAlignmentOfText(handle, style)
% sets the horizontal and vertical alignment options of a text object
VerticalAlignment = get(handle, 'VerticalAlignment');
HorizontalAlignment = get(handle, 'HorizontalAlignment');
horizontal = '';
vertical = '';
switch VerticalAlignment
case {'top', 'cap'}
vertical = 'below';
case {'baseline', 'bottom'}
vertical = 'above';
end
switch HorizontalAlignment
case 'left'
horizontal = 'right';
case 'right'
horizontal = 'left';
end
alignment = strtrim(sprintf('%s %s', vertical, horizontal));
if ~isempty(alignment)
style = opts_add(style, alignment);
end
% Set 'align' option that is needed for multiline text
style = opts_add(style, 'align', HorizontalAlignment);
end
% ==============================================================================
function [style] = getRotationOfText(m2t, handle, style)
% Add rotation, if existing
defaultRotation = 0.0;
rot = getOrDefault(handle, 'Rotation', defaultRotation);
if rot ~= defaultRotation
style = opts_add(style, 'rotate', sprintf(m2t.ff, rot));
end
end
% ==============================================================================
function [m2t,posString] = getPositionOfText(m2t, h)
% makes the tikz position string of a text object
pos = get(h, 'Position');
units = get(h, 'Units');
is3D = m2t.axes{end}.is3D;
% Deduce if text or textbox
type = get(h,'type');
if isempty(type) || strcmpi(type,'hggroup')
type = get(h,'ShapeType'); % Undocumented property valid from 2008a
end
switch type
case 'text'
if is3D
pos = applyHgTransform(m2t, pos);
npos = 3;
else
pos = pos(1:2);
npos = 2;
end
case {'textbox','textboxshape'}
% TODO:
% - size of the box (e.g. using node attributes minimum width / height)
% - Alignment of the resized box
pos = pos(1:2);
npos = 2;
otherwise
error('matlab2tikz:drawText', 'Unrecognized text type: %s.', type);
end
% Format according to units
switch units
case 'normalized'
type = 'rel axis cs:';
fmtUnit = '';
case 'data'
type = 'axis cs:';
fmtUnit = '';
% Let Matlab do the conversion of any unit into cm
otherwise
type = '';
fmtUnit = 'cm';
if ~strcmpi(units, 'centimeters')
% Save old pos, set units to cm, query pos, reset
% NOTE: cannot use copyobj since it is buggy in R2014a, see
% http://www.mathworks.com/support/bugreports/368385
oldPos = get(h, 'Position');
set(h,'Units','centimeters')
pos = get(h, 'Position');
pos = pos(1:npos);
set(h,'Units',units,'Position',oldPos)
end
end
posString = cell(1,npos);
for ii = 1:npos
posString{ii} = formatDim(pos(ii), fmtUnit);
end
posString = sprintf('(%s%s)',type,join(m2t,posString,','));
m2t = disableClippingInCurrentAxes(m2t, pos);
end
% ==============================================================================
function m2t = disableClippingInCurrentAxes(m2t, pos)
% Disables clipping in the current axes if the `pos` vector lies outside
% the limits of the axes.
xlim = getOrDefault(m2t.current.gca, 'XLim',[-Inf +Inf]);
ylim = getOrDefault(m2t.current.gca, 'YLim',[-Inf +Inf]);
zlim = getOrDefault(m2t.current.gca, 'ZLim',[-Inf +Inf]);
is3D = m2t.axes{end}.is3D;
xOutOfRange = pos(1) < xlim(1) || pos(1) > xlim(2);
yOutOfRange = pos(2) < ylim(1) || pos(2) > ylim(2);
zOutOfRange = is3D && (pos(3) < zlim(1) || pos(3) > zlim(2));
if xOutOfRange || yOutOfRange || zOutOfRange
m2t = m2t_addAxisOption(m2t, 'clip', 'false');
end
end
% ==============================================================================
function [m2t, str] = drawRectangle(m2t, h)
str = '';
% there may be some text objects floating around a Matlab figure which
% are handled by other subfunctions (labels etc.) or don't need to be
% handled at all
if ~isVisible(h) || isOff(get(h, 'HandleVisibility'))
return;
end
% TODO handle Curvature = [0.8 0.4]
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Get draw options.
[m2t, lineOptions] = getLineOptions(m2t, h);
[m2t, lineOptions] = getRectangleFaceOptions(m2t, h, lineOptions);
[m2t, lineOptions] = getRectangleEdgeOptions(m2t, h, lineOptions);
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pos = pos2dims(get(h, 'Position'));
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% plot the thing
lineOpts = opts_print(lineOptions);
str = sprintf(['\\draw[%s] (axis cs:',m2t.ff,',',m2t.ff, ')', ...
' rectangle (axis cs:',m2t.ff,',',m2t.ff,');\n'], ...
lineOpts, pos.left, pos.bottom, pos.right, pos.top);
end
% ==============================================================================
function [m2t, drawOptions] = getRectangleFaceOptions(m2t, h, drawOptions)
% draws the face (i.e. fill) of a Rectangle
faceColor = get(h, 'FaceColor');
isAnnotation = strcmpi(get(h,'type'),'rectangleshape') || ...
strcmpi(getOrDefault(h,'ShapeType',''),'rectangle');
isFlatColor = strcmpi(faceColor, 'flat');
if ~(isNone(faceColor) || (isAnnotation && isFlatColor))
[m2t, xFaceColor] = getColor(m2t, h, faceColor, 'patch');
drawOptions = opts_add(drawOptions, 'fill', xFaceColor);
end
end
% ==============================================================================
function [m2t, drawOptions] = getRectangleEdgeOptions(m2t, h, drawOptions)
% draws the edges of a rectangle
edgeColor = get(h, 'EdgeColor');
lineStyle = get(h, 'LineStyle');
if isNone(lineStyle) || isNone(edgeColor)
drawOptions = opts_add(drawOptions, 'draw', 'none');
else
[m2t, drawOptions] = setColor(m2t, h, drawOptions, 'draw', edgeColor);
end
end
% ==============================================================================
function [m2t,opts,s] = shaderOpts(m2t, handle, selectedType)
% SHADEROPTS Returns the shader, fill and draw options for patches, surfs and meshes
%
% SHADEROPTS(M2T, HANDLE, SELECTEDTYPE) Where SELECTEDTYPE should either
% be 'surf' or 'patch'
%
%
% [...,OPTS, S] = SHADEROPTS(...)
% OPTS is a M by 2 cell array with Key/Value pairs
% S is a struct with fields, e.g. 'faceColor', to be re-used by the
% caller
% Initialize
opts = opts_new;
s.hasOneEdgeColor = false;
s.hasOneFaceColor = false;
% Get relevant Face and Edge color properties
s.faceColor = get(handle, 'FaceColor');
s.edgeColor = get(handle, 'EdgeColor');
if isNone(s.faceColor) && isNone(s.edgeColor)
s.plotType = 'none';
s.hasOneEdgeColor = true;
elseif isNone(s.faceColor)
s.plotType = 'mesh';
s.hasOneFaceColor = true;
[m2t, opts, s] = shaderOptsMesh(m2t, handle, opts, s);
else
s.plotType = selectedType;
[m2t, opts, s] = shaderOptsSurfPatch(m2t, handle, opts, s);
end
end
% ==============================================================================
function [m2t, opts, s] = shaderOptsMesh(m2t, handle, opts, s)
% Edge 'interp'
if strcmpi(s.edgeColor, 'interp')
opts = opts_add(opts,'shader','flat');
% Edge RGB
else
s.hasOneEdgeColor = true;
[m2t, xEdgeColor] = getColor(m2t, handle, s.edgeColor, 'patch');
opts = opts_add(opts,'color',xEdgeColor);
end
end
% ==============================================================================
function [m2t, opts, s] = shaderOptsSurfPatch(m2t, handle, opts, s)
% gets the shader options for surface patches
% Set opacity if FaceAlpha < 1 in MATLAB
s.faceAlpha = get(handle, 'FaceAlpha');
if isnumeric(s.faceAlpha) && s.faceAlpha ~= 1.0
opts = opts_add(opts,'fill opacity',sprintf(m2t.ff,s.faceAlpha));
end
% Set opacity if EdgeAlpha < 1 in MATLAB
s.edgeAlpha = get(handle, 'EdgeAlpha');
if isnumeric(s.edgeAlpha) && s.edgeAlpha ~= 1.0
opts = opts_add(opts,'draw opacity',sprintf(m2t.ff,s.edgeAlpha));
end
if isNone(s.edgeColor) % Edge 'none'
[m2t, opts, s] = shaderOptsSurfPatchEdgeNone(m2t, handle, opts, s);
elseif strcmpi(s.edgeColor, 'interp') % Edge 'interp'
[m2t, opts, s] = shaderOptsSurfPatchEdgeInterp(m2t, handle, opts, s);
elseif strcmpi(s.edgeColor, 'flat') % Edge 'flat'
[m2t, opts, s] = shaderOptsSurfPatchEdgeFlat(m2t, handle, opts, s);
else % Edge RGB
[m2t, opts, s] = shaderOptsSurfPatchEdgeRGB(m2t, handle, opts, s);
end
end
% ==============================================================================
function [m2t, opts, s] = shaderOptsSurfPatchEdgeNone(m2t, handle, opts, s)
% gets the shader options for surface patches without edges
s.hasOneEdgeColor = true; % consider void as true
if strcmpi(s.faceColor, 'flat')
opts = opts_add(opts,'shader','flat');
elseif strcmpi(s.faceColor, 'interp');
opts = opts_add(opts,'shader','interp');
else
s.hasOneFaceColor = true;
[m2t,xFaceColor] = getColor(m2t, handle, s.faceColor, 'patch');
opts = opts_add(opts,'fill',xFaceColor);
end
end
function [m2t, opts, s] = shaderOptsSurfPatchEdgeInterp(m2t, handle, opts, s)
% gets the shader options for surface patches with interpolated edge colors
if strcmpi(s.faceColor, 'interp')
opts = opts_add(opts,'shader','interp');
elseif strcmpi(s.faceColor, 'flat')
opts = opts_add(opts,'shader','faceted');
else
s.hasOneFaceColor = true;
[m2t,xFaceColor] = getColor(m2t, handle, s.faceColor, 'patch');
opts = opts_add(opts,'fill',xFaceColor);
end
end
function [m2t, opts, s] = shaderOptsSurfPatchEdgeFlat(m2t, handle, opts, s)
% gets the shader options for surface patches with flat edge colors, i.e. the
% vertex color
if strcmpi(s.faceColor, 'flat')
opts = opts_add(opts,'shader','flat corner');
elseif strcmpi(s.faceColor, 'interp')
warnFacetedInterp(m2t);
opts = opts_add(opts,'shader','faceted interp');
else
s.hasOneFaceColor = true;
opts = opts_add(opts,'shader','flat corner');
[m2t,xFaceColor] = getColor(m2t, handle, s.faceColor, 'patch');
opts = opts_add(opts,'fill',xFaceColor);
end
end
function [m2t, opts, s] = shaderOptsSurfPatchEdgeRGB(m2t, handle, opts, s)
% gets the shader options for surface patches with fixed (RGB) edge color
s.hasOneEdgeColor = true;
[m2t, xEdgeColor] = getColor(m2t, handle, s.edgeColor, 'patch');
if isnumeric(s.faceColor)
s.hasOneFaceColor = true;
[m2t, xFaceColor] = getColor(m2t, handle, s.faceColor, 'patch');
opts = opts_add(opts,'fill',xFaceColor);
opts = opts_add(opts,'faceted color',xEdgeColor);
elseif strcmpi(s.faceColor,'interp')
warnFacetedInterp(m2t);
opts = opts_add(opts,'shader','faceted interp');
opts = opts_add(opts,'faceted color',xEdgeColor);
else
opts = opts_add(opts,'shader','flat corner');
opts = opts_add(opts,'draw',xEdgeColor);
end
end
% ==============================================================================
function warnFacetedInterp(m2t)
% warn the user about the space implications of "shader=faceted interp"
userWarning(m2t, ...
['A 3D plot with "shader = faceted interp" is being produced.\n', ...
'This may produce big and sluggish PDF files.\n', ...
'See %s and Section 4.6.6 of the pgfplots manual for workarounds.'], ...
issueUrl(m2t, 693, true));
end
% ==============================================================================
function url = issueUrl(m2t, number, forOutput)
% Produces the URL for an issue report in the GitHub repository.
% When the `forOutput` flag is set, this format the URL for printing to the
% MATLAB terminal.
if ~exist('forOutput','var') || isempty(forOutput)
forOutput = false;
end
url = sprintf('%s/%d', m2t.about.issues, number);
if forOutput
url = clickableUrl(url, sprintf('#%d', number));
end
end
% ==============================================================================
function url = clickableUrl(url, title)
% Produce a clickable URL for outputting to the MATLAB terminal
if ~exist('title','var') || isempty(title)
title = url;
end
switch getEnvironment()
case 'MATLAB'
url = sprintf('<a href="%s">%s</a>', url, title);
case 'Octave'
% just use the URL and discard the title since Octave doesn't
% support HTML tags in its output.
otherwise
errorUnknownEnvironment();
end
end
% ==============================================================================
function [m2t, str] = drawScatterPlot(m2t, h)
% DRAWSCATTERPLOT Draws a scatter plot
%
% A scatter plot is a plot containing only markers and where the
% size and/or color of each marker can be changed independently.
%
% References for TikZ code:
% - http://tex.stackexchange.com/questions/197270/how-to-plot-scatter-points-using-pgfplots-with-color-defined-from-table-rgb-valu
% - http://tex.stackexchange.com/questions/98646/multiple-different-meta-for-marker-color-and-marker-size
%
% See also: scatter
str = '';
if ~isVisible(h)
return; % there is nothing to plot
end
dataInfo = getDataInfo(h, 'X','Y','Z','C','Size');
markerInfo = getMarkerInfo(m2t, h);
if isempty(dataInfo.C) && strcmpi(getEnvironment(), 'Octave')
dataInfo.C = get(h, 'MarkerEdgeColor');
end
%TODO: check against getMarkerOptions() for duplicated code
dataInfo.Size = tryToMakeScalar(dataInfo.Size, m2t.tol);
% Rescale marker size (not definitive, follow discussion in #316)
% Prescale marker size for octave
if strcmpi(getEnvironment(), 'Octave')
dataInfo.Size = dataInfo.Size.^2/2;
end
dataInfo.Size = translateMarkerSize(m2t, markerInfo.style, sqrt(dataInfo.Size)/2);
drawOptions = opts_new();
%% Determine if we are drawing an actual scatter plot
hasDifferentSizes = numel(dataInfo.Size) ~= 1;
hasDifferentColors = numel(dataInfo.C) ~= 3;
isaScatter = hasDifferentSizes || hasDifferentColors;
if isaScatter
drawOptions = opts_add(drawOptions, 'scatter');
end
%TODO: we need to set the scatter source
drawOptions = opts_add(drawOptions, 'only marks');
drawOptions = opts_add(drawOptions, 'mark', markerInfo.tikz);
if length(dataInfo.C) == 3
% gets options specific to scatter plots with a single color
% No special treatment for the colors or markers are needed.
% All markers have the same color.
[m2t, xcolor, hasFaceColor] = getColorOfMarkers(m2t, h, 'MarkerFaceColor', dataInfo.C);
[m2t, ecolor, hasEdgeColor] = getColorOfMarkers(m2t, h, 'MarkerEdgeColor', dataInfo.C);
if length(dataInfo.Size) == 1;
drawOptions = opts_addSubOpts(drawOptions, 'mark options', ...
markerInfo.options);
drawOptions = opts_add(drawOptions, 'mark size', ...
sprintf('%.4fpt', dataInfo.Size)); % FIXME: investigate whether to use `m2t.ff`
if hasEdgeColor
drawOptions = opts_add(drawOptions, 'draw', ecolor);
else
drawOptions = opts_add(drawOptions, 'color', xcolor); %TODO: why do we even need this one?
end
if hasFaceColor
drawOptions = opts_add(drawOptions, 'fill', xcolor);
end
else % if changing marker size but same color on all marks
markerOptions = opts_new();
markerOptions = opts_addSubOpts(markerOptions, 'mark options', ...
markerInfo.options);
if hasEdgeColor
markerOptions = opts_add(markerOptions, 'draw', ecolor);
else
markerOptions = opts_add(markerOptions, 'draw', xcolor);
end
if hasFaceColor
markerOptions = opts_add(markerOptions, 'fill', xcolor);
end
% for changing marker size, the 'scatter' option has to be added
drawOptions = opts_add(drawOptions, 'color', xcolor);
drawOptions = opts_addSubOpts(drawOptions, 'mark options', ...
markerInfo.options);
if ~hasFaceColor
drawOptions = opts_add(drawOptions, ...
'scatter/use mapped color', xcolor);
else
drawOptions = opts_addSubOpts(drawOptions, ...
'scatter/use mapped color', markerOptions);
end
end
elseif size(dataInfo.C,2) == 3
% scatter plots with each marker a different RGB color (not yet supported!)
userWarning(m2t, 'Pgfplots cannot handle RGB scatter plots yet.');
% TODO Get this in order as soon as Pgfplots can do "scatter rgb".
% See e.g. http://tex.stackexchange.com/questions/197270 and #433
else
% scatter plot where the colors are set using a color map
markerOptions = opts_new();
markerOptions = opts_addSubOpts(markerOptions, 'mark options', ...
markerInfo.options);
if markerInfo.hasEdgeColor && markerInfo.hasFaceColor
[m2t, ecolor] = getColor(m2t, h, markerInfo.EdgeColor, 'patch');
markerOptions = opts_add(markerOptions, 'draw', ecolor);
else
markerOptions = opts_add(markerOptions, 'draw', 'mapped color');
end
if markerInfo.hasFaceColor
markerOptions = opts_add(markerOptions, 'fill', 'mapped color');
end
if numel(dataInfo.Size) == 1
drawOptions = opts_add(drawOptions, 'mark size', ...
sprintf('%.4fpt', dataInfo.Size)); % FIXME: investigate whether to use `m2t.ff`
else
%TODO: warn the user about this. It is not currently supported.
end
drawOptions = opts_add(drawOptions, 'scatter src', 'explicit');
drawOptions = opts_addSubOpts(drawOptions, 'scatter/use mapped color', ...
markerOptions);
% Add color map.
m2t = m2t_addAxisOption(m2t, matlab2pgfplotsColormap(m2t, m2t.current.colormap), []);
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Plot the thing.
[env, data, metaPart, columns] = organizeScatterData(m2t, dataInfo);
if hasDifferentSizes
drawOptions = opts_append(drawOptions, 'visualization depends on', ...
'{\thisrow{size} \as \perpointmarksize}');
drawOptions = opts_add(drawOptions, ...
'scatter/@pre marker code/.append style', ...
'{/tikz/mark size=\perpointmarksize}');
end
% The actual printing.
[m2t, table, tableOptions] = makeTable(m2t, columns, data);
tableOptions = opts_merge(tableOptions, metaPart);
% Print
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\%s[%s] table[%s]{%s};\n',...
env, drawOpts, tabOpts, table);
end
% ==============================================================================
function dataInfo = getDataInfo(h, varargin)
% retrieves the "*Data fields from a HG object
% When no names are specified, it assumes 'X','Y','Z' is requested
if nargin == 1
fields = {'X','Y','Z'};
else
fields = varargin;
end
dataInfo = struct();
for iField = 1:numel(fields)
name = fields{iField};
dataInfo.(name) = get(h, [name 'Data']);
end
end
% ==============================================================================
function value = tryToMakeScalar(value, tolerance)
% make a vector into a scalar when all its components are equal
if ~exist('tolerance','var')
tolerance = 0; % do everything perfectly
end
if all(abs(value - value(1)) <= tolerance)
value = value(1);
end
end
% ==============================================================================
function marker = getMarkerInfo(m2t, h, markOptions)
% gets marker-related options as a struct
if ~exist('markOptions','var') || isempty(markOptions)
markOptions = opts_new();
end
marker = struct();
marker.style = get(h, 'Marker');
marker.FaceColor = get(h, 'MarkerFaceColor');
marker.EdgeColor = get(h, 'MarkerEdgeColor');
marker.hasFaceColor = ~isNone(marker.FaceColor);
marker.hasEdgeColor = ~isNone(marker.EdgeColor);
[marker.tikz, marker.options] = translateMarker(m2t, marker.style, ...
markOptions, marker.hasFaceColor);
end
% ==============================================================================
function [env, data, metaOptions, columns] = organizeScatterData(m2t, dataInfo)
% reorganizes the {X,Y,Z,S} data into a single matrix
metaOptions = opts_new();
xData = dataInfo.X;
yData = dataInfo.Y;
zData = dataInfo.Z;
cData = dataInfo.C;
sData = dataInfo.Size;
% add the actual data
if ~m2t.axes{end}.is3D
env = 'addplot';
columns = {'x','y'};
data = [xData(:), yData(:)];
else
env = 'addplot3';
columns = {'x','y','z'};
data = applyHgTransform(m2t, [xData(:), yData(:), zData(:)]);
end
% add marker sizes
if length(sData) ~= 1
columns = [columns, {'size'}];
data = [data, sData(:)];
end
% add color data
if length(cData) == 3
% If size(cData,1)==1, then all the colors are the same and have
% already been accounted for above.
elseif size(cData,2) == 3
%TODO Hm, can't deal with this?
%[m2t, col] = rgb2colorliteral(m2t, cData(k,:));
%str = strcat(str, sprintf(' [%s]\n', col));
columns = [columns, {'R','G','B'}];
data = [data, cData(:,1), cData(:,2), cData(:,3)];
else
columns = [columns, {'color'}];
metaOptions = opts_add(metaOptions, 'meta', 'color');
data = [data, cData(:)];
end
end
% ==============================================================================
function [m2t, xcolor, hasColor] = getColorOfMarkers(m2t, h, name, cData)
color = get(h, name);
hasColor = ~isNone(color);
if hasColor && ~strcmpi(color,'flat');
[m2t, xcolor] = getColor(m2t, h, color, 'patch');
else
[m2t, xcolor] = getColor(m2t, h, cData, 'patch');
end
end
% ==============================================================================
function [m2t, str] = drawHistogram(m2t, h)
% Takes care of plots like the ones produced by MATLAB's histogram function.
% The main pillar is Pgfplots's '{x,y}bar' plot.
%
% TODO Get rid of code duplication with 'drawAxes'.
% Do nothing if plot is invisible
str = '';
if ~isVisible(h)
return;
end
% Init drawOptions
drawOptions = opts_new();
% Data
binEdges = get(h, 'BinEdges');
binValue = get(h, 'Values');
data = [binEdges(:), [binValue(:); binValue(end)]];
% Check for orientation of the bars
isHorizontal = ~strcmpi(get(h, 'Orientation'), 'vertical');
if isHorizontal
drawOptions = opts_add(drawOptions, 'xbar interval');
data = fliplr(data);
else
drawOptions = opts_add(drawOptions, 'ybar interval');
end
% Get the draw options for the bars
[m2t, drawOptions] = getPatchDrawOptions(m2t, h, drawOptions);
% Make table
[m2t, table, tableOptions] = makeTable(m2t, {'x','y'},data);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s] {%s};\n', ...
drawOpts, tabOpts, table);
end
% ==============================================================================
function [m2t, str] = drawBarseries(m2t, h)
% Takes care of plots like the ones produced by MATLAB's bar function.
% The main pillar is Pgfplots's '{x,y}bar' plot.
%
% TODO Get rid of code duplication with 'drawAxes'.
% Do nothing if plot is invisible
str = '';
if ~isVisible(h)
return;
end
% Init drawOptions
drawOptions = opts_new();
% Check for orientation of the bars and their layout
isHorizontal = isOn(get(h, 'Horizontal'));
if isHorizontal
barType = 'xbar';
else
barType = 'ybar';
end
% Get the draw options for the layout
[m2t, drawOptions] = setBarLayoutOfBarSeries(m2t, h, barType, drawOptions);
% Get the draw options for the bars
[m2t, drawOptions] = getPatchDrawOptions(m2t, h, drawOptions);
% Add 'log origin = infty' if BaseValue differs from zero (log origin=0 is
% the default behaviour since Pgfplots v1.5).
baseValue = get(h, 'BaseValue');
if baseValue ~= 0.0
m2t = m2t_addAxisOption(m2t, 'log origin', 'infty');
%TODO: wait for pgfplots to implement other base values (see #438)
end
% Generate the tikz table
xData = get(h, 'XData');
yData = get(h, 'YData');
if isHorizontal
[yDataPlot, xDataPlot] = deal(xData, yData); % swap values
else
[xDataPlot, yDataPlot] = deal(xData, yData);
end
[m2t, table, tableOptions] = makeTable(m2t, '', xDataPlot, '', yDataPlot);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s] {%s};\n', ...
drawOpts, tabOpts, table);
% Add a baseline if appropriate
[m2t, baseline] = drawBaseline(m2t,h,isHorizontal);
str = [str, baseline];
end
% ==============================================================================
function BarWidth = getBarWidthInAbsolutUnits(h)
% determines the width of a bar in a bar plot
XData = get(h,'XData');
BarWidth = get(h, 'BarWidth');
if length(XData) > 1
BarWidth = min(diff(XData)) * BarWidth;
end
end
% ==============================================================================
function [m2t, drawOptions] = setBarLayoutOfBarSeries(m2t, h, barType, drawOptions)
% sets the options specific to a bar layour (grouped vs stacked)
barlayout = get(h, 'BarLayout');
switch barlayout
case 'grouped' % grouped bar plots
% Get number of bars series and bar series id
[numBarSeries, barSeriesId] = getNumBarAndId(h);
% Maximum group width relative to the minimum distance between two
% x-values. See <MATLAB>/toolbox/matlab/specgraph/makebars.m
maxGroupWidth = 0.8;
if numBarSeries == 1
groupWidth = 1.0;
else
groupWidth = min(maxGroupWidth, numBarSeries/(numBarSeries+1.5));
end
% Calculate the width of each bar and the center point shift as in
% makebars.m
% Get the shifts of the bar centers.
% In case of numBars==1, this returns 0,
% In case of numBars==2, this returns [-1/4, 1/4],
% In case of numBars==3, this returns [-1/3, 0, 1/3],
% and so forth.
% assumedBarWidth = groupWidth/numBarSeries; % assumption
% barShift = (barSeriesId - 0.5) * assumedBarWidth - groupWidth/2;
% FIXME #785: The previous version of barshift lead to
% regressions, as the bars were stacked.
% Instead remove the calculation of barShift and add x/ybar to
% the axis so that pgf determines it automatically.
% From http://www.mathworks.com/help/techdoc/ref/bar.html:
% bar(...,width) sets the relative bar width and controls the
% separation of bars within a group. The default width is 0.8, so if
% you do not specify X, the bars within a group have a slight
% separation. If width is 1, the bars within a group touch one
% another. The value of width must be a scalar.
assumedBarWidth = groupWidth/numBarSeries; % assumption
barWidth = getBarWidthInAbsolutUnits(h) * assumedBarWidth;
% Bar type
drawOptions = opts_add(drawOptions, barType);
% Bar width
drawOptions = opts_add(drawOptions, 'bar width', formatDim(barWidth, ''));
% The bar shift auto feature was introduced in pgfplots 1.13
m2t = needsPgfplotsVersion(m2t, [1,13]);
m2t = m2t_addAxisOption(m2t, 'bar shift auto');
case 'stacked' % stacked plots
% Pass option to parent axis & disallow anything but stacked plots
% Make sure this happens exactly *once*.
if ~m2t.axes{end}.barAddedAxisOption;
barWidth = getBarWidthInAbsolutUnits(h);
m2t = m2t_addAxisOption(m2t, 'bar width', formatDim(barWidth,''));
m2t.axes{end}.barAddedAxisOption = true;
end
% Somewhere between pgfplots 1.5 and 1.8 and starting
% again from 1.11, the option {x|y}bar stacked can be applied to
% \addplot instead of the figure and thus allows to combine stacked
% bar plots and other kinds of plots in the same axis.
% Thus, it is advisable to use pgfplots 1.11. In older versions, the
% plot will only contain a single bar series, but should compile fine.
m2t = needsPgfplotsVersion(m2t, [1,11]);
drawOptions = opts_add(drawOptions, [barType ' stacked']);
otherwise
error('matlab2tikz:drawBarseries', ...
'Don''t know how to handle BarLayout ''%s''.', barlayout);
end
end
% ==============================================================================
function [numBarSeries, barSeriesId] = getNumBarAndId(h)
% Get number of bars series and bar series id
prop = switchMatOct('BarPeers', 'bargroup');
bargroup = get(h, prop);
numBarSeries = numel(bargroup);
if isHG2
% In HG2, BarPeers are sorted in reverse order wrt HG1
bargroup = bargroup(end:-1:1);
elseif strcmpi(getEnvironment, 'MATLAB')
% In HG1, h is a double but bargroup a graphic object. Cast h to a
% graphic object
h = handle(h);
else
% In Octave, the bargroup is a replicated cell array. Pick first
if iscell(bargroup)
bargroup = bargroup{1};
end
end
% Get bar series Id
[dummy, barSeriesId] = ismember(h, bargroup);
end
% ==============================================================================
function [m2t,str] = drawBaseline(m2t,hparent,isVertical)
% DRAWBASELINE Draws baseline for bar and stem plots
%
% Notes:
% - In HG2, the baseline is a specific object child of a bar or stem
% plot. So, handleAllChildren() won't find a line in the axes to plot as
% the baseline.
% - The baseline is horizontal for vertical bar and stem plots and is
% vertical for horixontal barplots. The ISVERTICAL input refers to the
% baseline.
% - We do not plot baselines with a BaseValue different from 0 because
% pgfplots does not support shifts in the BaseValue, e.g. see #438.
% We either implement our own data shifting or wait for pgfplots.
if ~exist('isVertical','var')
isVertical = false;
end
str = '';
baseValue = get(hparent, 'BaseValue');
if isOff(get(hparent,'ShowBaseLine')) || ~isHG2() || baseValue ~= 0
return
end
hBaseLine = get(hparent,'BaseLine');
% Line options of the baseline
[m2t, lineOptions] = getLineOptions(m2t, hparent);
color = get(hBaseLine, 'Color');
[m2t, lineColor] = getColor(m2t, hBaseLine, color, 'patch');
drawOptions = opts_new();
drawOptions = opts_add(drawOptions, 'forget plot');
drawOptions = opts_add(drawOptions, 'color', lineColor);
drawOptions = opts_merge(drawOptions, lineOptions);
% Get data
if isVertical
xData = repmat(baseValue,1,2);
yData = get(m2t.current.gca,'Ylim');
else
xData = get(m2t.current.gca,'Xlim');
yData = repmat(baseValue,1,2);
end
[m2t, table, tableOptions] = makeTable(m2t, '', xData, '', yData);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s] {%s};\n', ...
drawOpts, tabOpts, table);
end
% ==============================================================================
function [m2t, str] = drawAreaSeries(m2t, h)
% Takes care of MATLAB's area plots.
%
% TODO Get rid of code duplication with 'drawAxes'.
% Do nothing if plot is invisible
str = '';
if ~isVisible(h)
return;
end
% Init drawOptions
drawOptions = opts_new();
% Get the draw options for the bars
[m2t, drawOptions] = getPatchDrawOptions(m2t, h, drawOptions);
if ~isfield(m2t, 'addedAreaOption') || isempty(m2t.addedAreaOption) || ~m2t.addedAreaOption
% Add 'area style' to axes options.
m2t = m2t_addAxisOption(m2t, 'area style');
m2t = m2t_addAxisOption(m2t, 'stack plots', 'y');
m2t.addedAreaOption = true;
end
% Toggle legend entry
drawOptions = maybeShowInLegend(m2t.currentHandleHasLegend, drawOptions);
% Generate the tikz table
xData = get(h, 'XData');
yData = get(h, 'YData');
[m2t, table, tableOptions] = makeTable(m2t, '', xData, '', yData);
% Print out
drawOpts = opts_print(drawOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s]{%s}\n\\closedcycle;\n',...
drawOpts, tabOpts, table);
%TODO: shouldn't this be "\addplot[] table[] {}" instead?
end
% ==============================================================================
function [m2t, str] = drawStemSeries(m2t, h)
[m2t, str] = drawStemOrStairSeries_(m2t, h, 'ycomb');
% TODO: handle baseplane with stem3()
if m2t.axes{end}.is3D
return
end
[m2t, baseline] = drawBaseline(m2t,h);
str = [str, baseline];
end
function [m2t, str] = drawStairSeries(m2t, h)
[m2t, str] = drawStemOrStairSeries_(m2t, h, 'const plot');
end
function [m2t, str] = drawStemOrStairSeries_(m2t, h, plotType)
% Do nothing if plot is invisible
str = '';
if ~isLineVisible(h)
return % nothing to plot!
end
% deal with draw options
color = get(h, 'Color');
[m2t, plotColor] = getColor(m2t, h, color, 'patch');
[m2t, lineOptions] = getLineOptions(m2t, h);
[m2t, markerOptions] = getMarkerOptions(m2t, h);
drawOptions = opts_new();
drawOptions = opts_add(drawOptions, plotType);
drawOptions = opts_add(drawOptions, 'color', plotColor);
drawOptions = opts_merge(drawOptions, lineOptions, markerOptions);
% Toggle legend entry
drawOptions = maybeShowInLegend(m2t.currentHandleHasLegend, drawOptions);
drawOpts = opts_print(drawOptions);
% Generate the tikz table
xData = get(h, 'XData');
yData = get(h, 'YData');
if m2t.axes{end}.is3D
% TODO: account for hgtransform
zData = get(h, 'ZData');
[m2t, table, tableOptions] = makeTable(m2t, '', xData, '', yData, '', zData);
% Print out
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot3 [%s]\n table[%s] {%s};\n ', ...
drawOpts, tabOpts, table);
else
[m2t, table, tableOptions] = makeTable(m2t, '', xData, '', yData);
% Print out
tabOpts = opts_print(tableOptions);
str = sprintf('\\addplot[%s] table[%s] {%s};\n', ...
drawOpts, tabOpts, table);
end
end
% ==============================================================================
function [m2t, str] = drawQuiverGroup(m2t, h)
% Takes care of MATLAB's quiver plots.
str = '';
[x,y,z,u,v,w] = getAndRescaleQuivers(m2t,h);
is3D = m2t.axes{end}.is3D;
% prepare output
if is3D
name = 'addplot3';
else % 2D plotting
name = 'addplot';
end
variables = {'x', 'y', 'z', 'u', 'v', 'w'};
data = NaN(numel(x),6);
data(:,1) = x;
data(:,2) = y;
data(:,3) = z;
data(:,4) = u;
data(:,5) = v;
data(:,6) = w;
if ~is3D
data(:,[3 6]) = []; % remove Z-direction
variables([3 6]) = [];
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% gather the arrow options
showArrowHead = get(h, 'ShowArrowHead');
if ~isLineVisible(h) && ~showArrowHead
return
end
plotOptions = opts_new();
if showArrowHead
plotOptions = opts_add(plotOptions, '-Straight Barb');
signalDependency(m2t, 'tikzlibrary', 'arrows.meta');
else
plotOptions = opts_add(plotOptions, '-');
end
% Append the arrow style to the TikZ options themselves.
color = get(h, 'Color');
[m2t, lineOptions] = getLineOptions(m2t, h);
[m2t, arrowcolor] = getColor(m2t, h, color, 'patch');
plotOptions = opts_add(plotOptions, 'color', arrowcolor);
plotOptions = opts_merge(plotOptions, lineOptions);
% Define the quiver settings
quiverOptions = opts_new();
quiverOptions = opts_add(quiverOptions, 'u', '\thisrow{u}');
quiverOptions = opts_add(quiverOptions, 'v', '\thisrow{v}');
if is3D
quiverOptions = opts_add(quiverOptions, 'w', '\thisrow{w}');
arrowLength = '{sqrt((\thisrow{u})^2+(\thisrow{v})^2+(\thisrow{w})^2)}';
else
arrowLength = '{sqrt((\thisrow{u})^2+(\thisrow{v})^2)}';
end
plotOptions = opts_add(plotOptions, 'point meta', arrowLength);
plotOptions = opts_add(plotOptions, 'point meta min', '0');
if showArrowHead
arrowHeadOptions = opts_new();
% In MATLAB (HG1), the arrow head is constructed to have an angle of
% approximately 18.263 degrees in 2D as can be derived from the
% |quiver| function.
% In 3D, the angle is no longer constant but it is approximately
% the same as for 2D quiver plots. So let's make our life easy.
% |test/examples/example_quivers.m| covers the calculations.
arrowHeadOptions = opts_add(arrowHeadOptions, 'angle''', '18.263');
%TODO: scale the arrows more rigorously to match MATLAB behavior
% Currently, this is quite hard to do, since the size of the arrows
% is defined in pgfplots in absolute units (here we specify that those
% should be scaled up/down according to the data), while the data itself
% is in axis coordinates (or some scaled variant). I.e. we need the
% physical dimensions of the axis to compute the correct scaling!
%
% There is a "MaxHeadSize" property that plays a role.
% MaxHeadSize is said to be relative to the length of the quiver in the
% MATLAB documentation. However, in practice, there seems to be a SQRT
% involved somewhere (e.g. if u.^2 + v.^2 == 2, all MHS values >
% 1/sqrt(2) are capped to 1/sqrt(2)).
%
% NOTE: `set(h, 'MaxHeadSize')` is bugged in HG1 (not in HG2 or Octave)
% according to http://www.mathworks.com/matlabcentral/answers/96754
userInfo(m2t, ['Please change the "arrowHeadSize" option', ...
' if the size of the arrows is incorrect.']);
arrowHeadSize = sprintf(m2t.ff, abs(m2t.args.arrowHeadSize));
% Write out the actual scaling for TikZ.
% `\pgfplotspointsmetatransformed` is in the range [0, 1000], so
% divide by this span (as is done in the pgfplots manual) to normalize
% the arrow head size. First divide to avoid overflows.
arrowHeadOptions = opts_add(arrowHeadOptions, 'scale', ...
['{' arrowHeadSize '/1000*\pgfplotspointmetatransformed}']);
headStyle = ['-{Straight Barb[' opts_print(arrowHeadOptions) ']}'];
quiverOptions = opts_add(quiverOptions, 'every arrow/.append style', ...
['{' headStyle '}']);
end
plotOptions = opts_addSubOpts(plotOptions, 'quiver', quiverOptions);
[m2t, table, tableOptions] = makeTable(m2t, variables, data);
% Print out
plotOpts = opts_print(plotOptions);
tabOpts = opts_print(tableOptions);
str = sprintf('\\%s[%s]\n table[%s] {%s};\n', ...
name, plotOpts, tabOpts, table);
end
% ==============================================================================
function [x,y,z,u,v,w] = getAndRescaleQuivers(m2t, h)
% get and rescale the arrows from a quivergroup object
x = get(h, 'XData');
y = get(h, 'YData');
z = getOrDefault(h, 'ZData', []);
u = get(h, 'UData');
v = get(h, 'VData');
w = getOrDefault(h, 'WData', []);
is3D = m2t.axes{end}.is3D;
if ~is3D
z = 0;
w = 0;
end
% MATLAB uses a scaling algorithm to determine the size of the arrows.
% Before R2014b, the processed coordinates were available. This is no longer
% the case, so we have to re-implement it. In MATLAB it is implemented in
% the |quiver3| (and |quiver|) function.
if any(size(x)==1)
nX = sqrt(numel(x)); nY = nX;
else
[nY, nX] = size(x);
end
range = @(xyzData)(max(xyzData(:)) - min(xyzData(:)));
euclid = @(x,y,z)(sqrt(x.^2 + y.^2 + z.^2));
dx = range(x)/nX;
dy = range(y)/nY;
dz = range(z)/max(nX,nY);
dd = euclid(dx, dy, dz);
if dd > 0
vectorLength = euclid(u/dd,v/dd,w/dd);
maxLength = max(vectorLength(:));
else
maxLength = 1;
end
if isOn(getOrDefault(h, 'AutoScale', 'on'))
scaleFactor = getOrDefault(h,'AutoScaleFactor', 0.9) / maxLength;
else
scaleFactor = 1;
end
x = x(:).'; u = u(:).'*scaleFactor;
y = y(:).'; v = v(:).'*scaleFactor;
z = z(:).'; w = w(:).'*scaleFactor;
end
% ==============================================================================
function [m2t, str] = drawErrorBars(m2t, h)
% Takes care of MATLAB's error bar plots.
% Octave's error bar plots are handled as well.
[m2t, str] = drawLine(m2t, h);
% Even though this only calls |drawLine|, let's keep this wrapper
% such that the code is easier to read where it is called.
end
% ==============================================================================
function [yDeviations] = getYDeviations(h)
% Retrieves upper/lower uncertainty data
upDev = getOrDefault(h, 'UData', []);
loDev = getOrDefault(h, 'LData', []);
yDeviations = [upDev(:), loDev(:)];
end
% ==============================================================================
function [m2t, str] = drawEllipse(m2t, handle)
% Takes care of MATLAB's ellipse annotations.
drawOptions = opts_new();
p = get(handle,'position');
radius = p([3 4]) / 2;
center = p([1 2]) + radius;
color = get(handle, 'Color');
[m2t, xcolor] = getColor(m2t, handle, color, 'patch');
[m2t, lineOptions] = getLineOptions(m2t, handle);
filling = get(handle, 'FaceColor');
% Has a filling?
if isNone(filling)
drawOptions = opts_add(drawOptions, xcolor);
drawCommand = '\draw';
else
[m2t, xcolorF] = getColor(m2t, handle, filling, 'patch');
drawOptions = opts_add(drawOptions, 'draw', xcolor);
drawOptions = opts_add(drawOptions, 'fill', xcolorF);
drawCommand = '\filldraw';
end
drawOptions = opts_merge(drawOptions, lineOptions);
opt = opts_print(drawOptions);
str = sprintf('%s [%s] (axis cs:%g,%g) ellipse [x radius=%g, y radius=%g];\n', ...
drawCommand, opt, center, radius);
end
% ==============================================================================
function [m2t, str] = drawTextarrow(m2t, handle)
% Takes care of MATLAB's textarrow annotations.
% handleAllChildren to draw the arrow
[m2t, str] = handleAllChildren(m2t, handle);
% handleAllChildren ignores the text, unless hidden strings are shown
if ~m2t.args.showHiddenStrings
child = findall(handle, 'type', 'text');
[m2t, str{end+1}] = drawText(m2t, child);
end
end
% ==============================================================================
function [m2t, drawOptions] = getPatchDrawOptions(m2t, h, drawOptions)
% Determines the reoccurring draw options usually applied when drawing
% a patch/area/bar. These include EdgeColor, LineType, FaceColor/Alpha
% Get object for color;
if ~isempty(allchild(h))
% quite oddly, before MATLAB R2014b this value is stored in a child
% patch and not in the object itself
obj = allchild(h);
else % R2014b and newer
obj = h;
end
% Get the object type
type = get(h, 'Type');
% Face Color (inside of area)
faceColor = get(obj, 'FaceColor');
[m2t, drawOptions] = setColor(m2t, h, drawOptions, 'fill', faceColor, 'none');
% FaceAlpha (Not applicable for MATLAB2014a/b)
faceAlpha = getOrDefault(h, 'FaceAlpha', 'none');
if ~isNone(faceColor) && isnumeric(faceAlpha) && faceAlpha ~= 1.0
drawOptions = opts_add(drawOptions, 'fill opacity', sprintf(m2t.ff,faceAlpha));
end
% Define linestyle
[lineStyle, isDefaultLS] = getAndCheckDefault(type, h, 'LineStyle', '-');
if isNone(lineStyle)
drawOptions = opts_add(drawOptions, 'draw', 'none');
elseif ~isDefaultLS
drawOptions = opts_add(drawOptions, translateLineStyle(lineStyle));
end
% Check for the edge color. Only plot it if it is different from the
% face color and if there is a linestyle
edgeColor = get(h, 'EdgeColor');
if ~isNone(lineStyle) && ~isNone(edgeColor) && ~strcmpi(edgeColor,faceColor)
[m2t, drawOptions] = setColor(m2t, h, drawOptions, 'draw', edgeColor, 'none');
end
% Add 'area legend' to the options as otherwise the legend indicators
% will just highlight the edges.
if strcmpi(type, 'bar') || strcmpi(type, 'histogram')
drawOptions = opts_add(drawOptions, 'area legend');
end
end
% ==============================================================================
function out = linearFunction(X, Y)
% Return the linear function that goes through (X[1], Y[1]), (X[2], Y[2]).
out = @(x) (Y(2,:)*(x-X(1)) + Y(1,:)*(X(2)-x)) / (X(2)-X(1));
end
% ==============================================================================
function matlabColormap = pgfplots2matlabColormap(points, rgb, numColors)
% Translates a Pgfplots colormap to a MATLAB color map.
matlabColormap = zeros(numColors, 3);
% Point indices between which to interpolate.
I = [1, 2];
f = linearFunction(points(I), rgb(I,:));
for k = 1:numColors
x = (k-1)/(numColors-1) * points(end);
if x > points(I(2))
I = I + 1;
f = linearFunction(points(I), rgb(I,:));
end
matlabColormap(k,:) = f(x);
end
end
% ==============================================================================
function pgfplotsColormap = matlab2pgfplotsColormap(m2t, matlabColormap, name)
% Translates a MATLAB color map into a Pgfplots colormap.
if nargin < 3 || isempty(name), name = 'mymap'; end
% First check if we could use a default Pgfplots color map.
% Unfortunately, MATLAB and Pgfplots color maps will never exactly coincide
% except to the most simple cases such as blackwhite. This is because of a
% slight incompatibility of Pgfplots and MATLAB colormaps:
% In MATLAB, indexing goes from 1 through 64, whereas in Pgfplots you can
% specify any range, the default ones having something like
% (0: red, 1: yellow, 2: blue).
% To specify this exact color map in MATLAB, one would have to put 'red' at
% 1, blue at 64, and yellow in the middle of the two, 32.5 that is.
% Not really sure how MATLAB rounds here: 32, 33? Anyways, it will be
% slightly off and hence not match the Pgfplots color map.
% As a workaround, build the MATLAB-formatted colormaps of Pgfplots default
% color maps, and check if matlabColormap is close to it. If yes, take it.
% For now, comment out the color maps which haven't landed yet in Pgfplots.
pgfmaps = { %struct('name', 'colormap/autumn', ...
% 'points', [0,1], ...
% 'values', [[1,0,0];[1,1,0]]), ...
%struct('name', 'colormap/bled', ...
% 'points', 0:6, ...
% 'values', [[0,0,0];[43,43,0];[0,85,0];[0,128,128];[0,0,170];[213,0,213];[255,0,0]]/255), ...
%struct('name', 'colormap/bright', ...
% 'points', 0:7, ...
% 'values', [[0,0,0];[78,3,100];[2,74,255];[255,21,181];[255,113,26];[147,213,114];[230,255,0];[255,255,255]]/255), ...
%struct('name', 'colormap/bone', ...
% 'points', [0,3,6,8], ...
% 'values', [[0,0,0];[84,84,116];[167,199,199];[255,255,255]]/255), ...
%struct('name', 'colormap/cold', ...
% 'points', 0:3, ...
% 'values', [[0,0,0];[0,0,1];[0,1,1];[1,1,1]]), ...
%struct('name', 'colormap/copper', ...
% 'points', [0,4,5], ...
% 'values', [[0,0,0];[255,159,101];[255,199,127]]/255), ...
%struct('name', 'colormap/copper2', ...
% 'points', 0:4, ...
% 'values', [[0,0,0];[68,62,63];[170,112,95];[207,194,138];[255,255,255]]/255), ...
%struct('name', 'colormap/hsv', ...
% 'points', 0:6, ...
% 'values', [[1,0,0];[1,1,0];[0,1,0];[0,1,1];[0,0,1];[1,0,1];[1,0,0]]), ...
struct('name', 'colormap/hot', ...
'points', 0:3, ...
'values', [[0,0,1];[1,1,0];[1,0.5,0];[1,0,0]]), ... % TODO check this
struct('name', 'colormap/hot2', ...
'points', [0,3,6,8], ...
'values', [[0,0,0];[1,0,0];[1,1,0];[1,1,1]]), ...
struct('name', 'colormap/jet', ...
'points', [0,1,3,5,7,8], ...
'values', [[0,0,128];[0,0,255];[0,255,255];[255,255,0];[255,0,0];[128,0,0]]/255), ...
struct('name', 'colormap/blackwhite', ...
'points', [0,1], ...
'values', [[0,0,0];[1,1,1]]), ...
struct('name', 'colormap/bluered', ...
'points', 0:5, ...
'values', [[0,0,180];[0,255,255];[100,255,0];[255,255,0];[255,0,0];[128,0,0]]/255), ...
struct('name', 'colormap/cool', ...
'points', [0,1,2], ...
'values', [[255,255,255];[0,128,255];[255,0,255]]/255), ...
struct('name', 'colormap/greenyellow', ...
'points', [0,1], ...
'values', [[0,128,0];[255,255,0]]/255), ...
struct('name', 'colormap/redyellow', ...
'points', [0,1], ...
'values', [[255,0,0];[255,255,0]]/255), ...
struct('name', 'colormap/violet', ...
'points', [0,1,2], ...
'values', [[25,25,122];[255,255,255];[238,140,238]]/255) ...
};
% The tolerance is a subjective matter of course.
% Some figures:
% * The norm-distance between MATLAB's gray and bone is 6.8e-2.
% * The norm-distance between MATLAB's jet and Pgfplots's jet is 2.8e-2.
% * The norm-distance between MATLAB's hot and Pgfplots's hot2 is 2.1e-2.
tol = 5.0e-2;
for map = pgfmaps
numColors = size(matlabColormap, 1);
mmap = pgfplots2matlabColormap(map{1}.points, map{1}.values, numColors);
alpha = norm(matlabColormap - mmap) / sqrt(numColors);
if alpha < tol
userInfo(m2t, 'Found %s to be a pretty good match for your color map (||diff||=%g).', ...
map{1}.name, alpha);
pgfplotsColormap = map{1}.name;
return
end
end
% Build a custom color map.
% Loop over the data, stop at each spot where the linear
% interpolation is interrupted, and set a color mark there.
m = size(matlabColormap, 1);
steps = [1, 2];
% A colormap with a single color is valid in MATLAB but an error in
% pgfplots. Repeating the color produces the desired effect in this
% case.
if m==1
colors=[matlabColormap(1,:);matlabColormap(1,:)];
else
colors = [matlabColormap(1,:); matlabColormap(2,:)];
f = linearFunction(steps, colors);
k = 3;
while k <= m
if norm(matlabColormap(k,:) - f(k)) > 1.0e-10
% Add the previous step to the color list
steps(end) = k-1;
colors(end,:) = matlabColormap(k-1,:);
steps = [steps, k];
colors = [colors; matlabColormap(k,:)];
f = linearFunction(steps(end-1:end), colors(end-1:end,:));
end
k = k+1;
end
steps(end) = m;
colors(end,:) = matlabColormap(m,:);
end
% Get it in Pgfplots-readable form.
unit = 'pt';
colSpecs = cell(length(steps), 1);
for k = 1:length(steps)
x = steps(k)-1;
colSpecs{k} = sprintf('rgb(%d%s)=(%g,%g,%g)', x, unit, colors(k,:));
end
pgfplotsColormap = sprintf('colormap={%s}{[1%s] %s}',name, unit, join(m2t, colSpecs, '; '));
end
% ==============================================================================
function [m2t, fontStyle] = getFontStyle(m2t, handle)
fontStyle = '';
if strcmpi(get(handle, 'FontWeight'),'Bold')
fontStyle = sprintf('%s\\bfseries',fontStyle);
end
if strcmpi(get(handle, 'FontAngle'), 'Italic')
fontStyle = sprintf('%s\\itshape',fontStyle);
end
if ~all(get(handle, 'Color')==0)
color = get(handle, 'Color');
[m2t, col] = getColor(m2t, handle, color, 'patch');
fontStyle = sprintf('%s\\color{%s}', fontStyle, col);
end
if m2t.args.strictFontSize
fontSize = get(handle,'FontSize');
fontUnits = matlab2texUnits(get(handle,'FontUnits'), 'pt');
fontStyle = sprintf('\\fontsize{%d%s}{1em}%s\\selectfont',fontSize,fontUnits,fontStyle);
else
% don't try to be smart and "translate" MATLAB font sizes to proper LaTeX
% ones: it cannot be done. LaTeX uses semantic sizes (e.g. \small)
% whose actual dimensions depend on the document style, context, ...
end
if ~isempty(fontStyle)
fontStyle = opts_add(opts_new, 'font', fontStyle);
else
fontStyle = opts_new();
end
end
% ==============================================================================
function axisOptions = getColorbarOptions(m2t, handle)
% begin collecting axes options
axisOptions = opts_new();
cbarStyleOptions = opts_new();
[cbarTemplate, cbarStyleOptions] = getColorbarPosOptions(handle, ...
cbarStyleOptions);
% axis label and direction
if isHG2
% VERSION: Starting from R2014b there is only one field `label`.
% The colorbar's position determines, if it should be a x- or y-label.
if strcmpi(cbarTemplate, 'horizontal')
labelOption = 'xlabel';
else
labelOption = 'ylabel';
end
[m2t, cbarStyleOptions] = getLabel(m2t, handle, cbarStyleOptions, labelOption);
% direction
dirString = get(handle, 'Direction');
if ~strcmpi(dirString, 'normal') % only if not 'normal'
if strcmpi(cbarTemplate, 'horizontal')
dirOption = 'x dir';
else
dirOption = 'y dir';
end
cbarStyleOptions = opts_add(cbarStyleOptions, dirOption, dirString);
end
% TODO HG2: colorbar ticks and colorbar tick labels
else
% VERSION: Up to MATLAB R2014a and OCTAVE
[m2t, xo] = getAxisOptions(m2t, handle, 'x');
[m2t, yo] = getAxisOptions(m2t, handle, 'y');
xyo = opts_merge(xo, yo);
xyo = opts_remove(xyo, 'xmin','xmax','xtick','ymin','ymax','ytick');
cbarStyleOptions = opts_merge(cbarStyleOptions, xyo);
end
% title
[m2t, cbarStyleOptions] = getTitle(m2t, handle, cbarStyleOptions);
if m2t.args.strict
% Sampled colors.
numColors = size(m2t.current.colormap, 1);
axisOptions = opts_add(axisOptions, 'colorbar sampled');
cbarStyleOptions = opts_add(cbarStyleOptions, 'samples', ...
sprintf('%d', numColors+1));
if ~isempty(cbarTemplate)
userWarning(m2t, ...
- 'Pgfplots cannot deal with more than one colorbar option yet.');
%FIXME: can we get sampled horizontal color bars to work?
%FIXME: sampled colorbars should be inferred, not by using strict!
end
end
% Merge them together in axisOptions.
axisOptions = opts_add(axisOptions, strtrim(['colorbar ', cbarTemplate]));
if ~isempty(cbarStyleOptions)
axisOptions = opts_addSubOpts(axisOptions, ...
'colorbar style', cbarStyleOptions);
end
% do _not_ handle colorbar's children
end
% ==============================================================================
function [cbarTemplate, cbarStyleOptions] = getColorbarPosOptions(handle, cbarStyleOptions)
% set position, ticks etc. of a colorbar
loc = get(handle, 'Location');
cbarTemplate = '';
switch lower(loc) % case insensitive (MATLAB: CamelCase, Octave: lower case)
case 'north'
cbarTemplate = 'horizontal';
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
'{(0.5,0.97)}');
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor',...
'north');
cbarStyleOptions = opts_add(cbarStyleOptions,...
'xticklabel pos', 'lower');
cbarStyleOptions = opts_add(cbarStyleOptions, 'width',...
'0.97*\pgfkeysvalueof{/pgfplots/parent axis width}');
case 'south'
cbarTemplate = 'horizontal';
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
'{(0.5,0.03)}');
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor', ...
'south');
cbarStyleOptions = opts_add(cbarStyleOptions, ...
'xticklabel pos','upper');
cbarStyleOptions = opts_add(cbarStyleOptions, 'width',...
'0.97*\pgfkeysvalueof{/pgfplots/parent axis width}');
case 'east'
cbarTemplate = 'right';
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
'{(0.97,0.5)}');
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor', ...
'east');
cbarStyleOptions = opts_add(cbarStyleOptions, ...
'xticklabel pos','left');
cbarStyleOptions = opts_add(cbarStyleOptions, 'width',...
'0.97*\pgfkeysvalueof{/pgfplots/parent axis width}');
case 'west'
cbarTemplate = 'left';
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
'{(0.03,0.5)}');
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor',...
'west');
cbarStyleOptions = opts_add(cbarStyleOptions,...
'xticklabel pos', 'right');
cbarStyleOptions = opts_add(cbarStyleOptions, 'width',...
'0.97*\pgfkeysvalueof{/pgfplots/parent axis width}');
case 'eastoutside'
%cbarTemplate = 'right';
case 'westoutside'
cbarTemplate = 'left';
case 'northoutside'
% TODO move to top
cbarTemplate = 'horizontal';
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
'{(0.5,1.03)}');
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor',...
'south');
cbarStyleOptions = opts_add(cbarStyleOptions,...
'xticklabel pos', 'upper');
case 'southoutside'
cbarTemplate = 'horizontal';
case 'manual'
origUnits = get(handle,'Units');
assocAxes = get(handle,'Axes');
origAxesUnits = get(assocAxes,'Units');
set(handle,'Units','centimeters'); % Make sure we have
set(assocAxes,'Units','centimeters'); % same units
cbarDim = pos2dims(get(handle,'Position'));
cbarAxesDim = pos2dims(get(assocAxes,'Position'));
set(handle,'Units',origUnits); % Restore original
set(assocAxes,'Units',origAxesUnits); % units
center = @(dims) (dims.left + dims.right)/2;
centerCbar = center(cbarDim);
centerAxes = center(cbarAxesDim);
% Cases of colorbar axis locations (in or out) depending on center
% of colorbar relative to the center it's associated axes.
% According to matlab manual (R2016a) colorbars with Location 'manual'
% can only be vertical.
axisLoc = getOrDefault(handle, 'AxisLocation', 'out');
if centerCbar < centerAxes
if strcmp(axisLoc,'in')
cbarTemplate = 'right';
else
cbarTemplate = 'left';
end
else
if strcmp(axisLoc,'in')
cbarTemplate = 'left';
else
cbarTemplate = 'right';
end
end
% Using positions relative to associated axes
calcRelPos = @(pos1,pos2,ext2) (pos1-pos2)/ext2;
cbarRelPosX = calcRelPos(cbarDim.left,cbarAxesDim.left,cbarAxesDim.width);
cbarRelPosY = calcRelPos(cbarDim.bottom,cbarAxesDim.bottom,cbarAxesDim.height);
cbarRelHeight = cbarDim.height/cbarAxesDim.height;
cbarStyleOptions = opts_add(cbarStyleOptions, 'anchor',...
'south west');
cbarStyleOptions = opts_add(cbarStyleOptions, 'at',...
['{(' formatDim(cbarRelPosX) ','...
formatDim(cbarRelPosY) ')}']);
cbarStyleOptions = opts_add(cbarStyleOptions, 'height',...
[formatDim(cbarRelHeight),...
'*\pgfkeysvalueof{/pgfplots/parent axis height}']);
otherwise
error('matlab2tikz:getColorOptions:unknownLocation',...
'getColorbarOptions: Unknown ''Location'' %s.', loc)
end
end
% ==============================================================================
function [m2t, xcolor] = getColor(m2t, handle, color, mode)
% Handles MATLAB colors and makes them available to TikZ.
% This includes translation of the color value as well as explicit
% definition of the color if it is not available in TikZ by default.
%
% The variable 'mode' essentially determines what format 'color' can
% have. Possible values are (as strings) 'patch' and 'image'.
% check if the color is straight given in rgb
% -- notice that we need the extra NaN test with respect to the QUIRK
% below
if isRGBTuple(color)
% everything alright: rgb color here
[m2t, xcolor] = rgb2colorliteral(m2t, color);
else
switch lower(mode)
case 'patch'
[m2t, xcolor] = patchcolor2xcolor(m2t, color, handle);
case 'image'
m = size(color,1);
n = size(color,2);
xcolor = cell(m, n);
if ndims(color) == 3
for i = 1:m
for j = 1:n
[m2t, xc] = rgb2colorliteral(m2t, color(i,j, :));
xcolor{i, j} = xc;
end
end
elseif ndims(color) <= 2
[m2t, colorindex] = cdata2colorindex(m2t, color, handle);
for i = 1:m
for j = 1:n
[m2t, xc] = rgb2colorliteral(m2t, m2t.current.colormap(colorindex(i,j), :));
xcolor{i, j} = xc;
end
end
else
error('matlab2tikz:getColor:image:colorDims',...
'Image color data cannot have more than 3 dimensions');
end
otherwise
error(['matlab2tikz:getColor', ...
'Argument ''mode'' has illegal value ''%s''.'], ...
mode);
end
end
end
% ==============================================================================
function [m2t, xcolor] = patchcolor2xcolor(m2t, color, patchhandle)
% Transforms a color of the edge or the face of a patch to an xcolor literal.
if isnumeric(color)
[m2t, xcolor] = rgb2colorliteral(m2t, color);
elseif ischar(color)
switch color
case 'flat'
cdata = getCDataWithFallbacks(patchhandle);
color1 = cdata(1,1);
% RGB cdata
if ndims(cdata) == 3 && all(size(cdata) == [1,1,3])
[m2t,xcolor] = rgb2colorliteral(m2t, cdata);
% All same color
elseif all(isnan(cdata) | abs(cdata-color1)<1.0e-10)
[m2t, colorindex] = cdata2colorindex(m2t, color1, patchhandle);
[m2t, xcolor] = rgb2colorliteral(m2t, m2t.current.colormap(colorindex, :));
else
% Don't return anything meaningful and count on the caller
% to make something of it.
xcolor = [];
end
case 'auto'
try
color = get(patchhandle, 'Color');
catch
% From R2014b use an undocumented property if Color is
% not present
color = get(patchhandle, 'AutoColor');
end
[m2t, xcolor] = rgb2colorliteral(m2t, color);
case 'none'
% Before, we used to throw an error here. However, probably this
% is not necessary and actually harmful (#739).
xcolor = 'none';
otherwise
error('matlab2tikz:anycolor2rgb:UnknownColorModel',...
'Don''t know how to handle the color model ''%s''.',color);
end
else
error('patchcolor2xcolor:illegalInput', ...
'Input argument ''color'' not a string or numeric.');
end
end
% ==============================================================================
function cdata = getCDataWithFallbacks(patchhandle)
% Looks for CData at different places
cdata = getOrDefault(patchhandle, 'CData', []);
if isempty(cdata) || ~isnumeric(cdata)
child = allchild(patchhandle);
cdata = get(child, 'CData');
end
if isempty(cdata) || ~isnumeric(cdata)
% R2014b+: CData is implicit by the ordering of the siblings
siblings = allchild(get(patchhandle, 'Parent'));
cdata = find(siblings(end:-1:1)==patchhandle);
end
end
% ==============================================================================
function [m2t, colorindex] = cdata2colorindex(m2t, cdata, imagehandle)
% Transforms a color in CData format to an index in the color map.
% Only does something if CDataMapping is 'scaled', really.
if ~isnumeric(cdata) && ~islogical(cdata)
error('matlab2tikz:cdata2colorindex:unknownCDataType',...
'Don''t know how to handle CData ''%s''.',cdata);
end
axeshandle = m2t.current.gca;
% -----------------------------------------------------------------------
% For the following, see, for example, the MATLAB help page for 'image',
% section 'Image CDataMapping'.
try
mapping = get(imagehandle, 'CDataMapping');
catch
mapping = 'scaled';
end
switch mapping
case 'scaled'
% need to scale within clim
% see MATLAB's manual page for caxis for details
clim = get(axeshandle, 'clim');
m = size(m2t.current.colormap, 1);
colorindex = zeros(size(cdata));
idx1 = cdata <= clim(1);
idx2 = cdata >= clim(2);
idx3 = ~idx1 & ~idx2;
colorindex(idx1) = 1;
colorindex(idx2) = m;
% cdata may be of type uint8. Convert to double to avoid
% getting binary indices
colorindex(idx3) = fix(double(cdata(idx3)-clim(1)) / (clim(2)-clim(1)) *m) ...
+ 1;
case 'direct'
% direct index
colorindex = cdata;
otherwise
error('matlab2tikz:anycolor2rgb:unknownCDataMapping',...
'Unknown CDataMapping ''%s''.',cdatamapping);
end
end
% ==============================================================================
function [m2t, key, legendOpts] = getLegendOpts(m2t, handle)
lStyle = opts_new();
lStyle = getLegendPosition(m2t, handle, lStyle);
lStyle = getLegendOrientation(m2t, handle, lStyle);
lStyle = getLegendEntryAlignment(m2t, handle, lStyle);
% If the plot has 'legend boxoff', we have the 'not visible'
% property, so turn off line and background fill.
if ~isVisible(handle) || isOff(get(handle,'box'))
lStyle = opts_add(lStyle, 'fill', 'none');
lStyle = opts_add(lStyle, 'draw', 'none');
else
% handle colors
[edgeColor, isDfltEdge] = getAndCheckDefault('Legend', handle, ...
'EdgeColor', [1 1 1]);
if isNone(edgeColor)
lStyle = opts_add(lStyle, 'draw', 'none');
elseif ~isDfltEdge
[m2t, col] = getColor(m2t, handle, edgeColor, 'patch');
lStyle = opts_add(lStyle, 'draw', col);
end
[fillColor, isDfltFill] = getAndCheckDefault('Legend', handle, ...
'Color', [1 1 1]);
if isNone(fillColor)
lStyle = opts_add(lStyle, 'fill', 'none');
elseif ~isDfltFill
[m2t, col] = getColor(m2t, handle, fillColor, 'patch');
lStyle = opts_add(lStyle, 'fill', col);
end
end
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
key = 'legend style';
legendOpts = opts_print(lStyle);
legendOpts = ['{', legendOpts, '}'];
%TODO: just pass out the `lStyle` instead of `legendOpts`
end
% ==============================================================================
function [lStyle] = getLegendOrientation(m2t, handle, lStyle)
% handle legend orientation
ori = get(handle, 'Orientation');
switch lower(ori)
case 'horizontal'
numLegendEntries = sprintf('%d',length(get(handle, 'String')));
lStyle = opts_add(lStyle, 'legend columns', numLegendEntries);
case 'vertical'
% Use default.
otherwise
userWarning(m2t, [' Unknown legend orientation ''',ori,'''' ...
'. Choosing default (vertical).']);
end
end
% ==============================================================================
function [lStyle] = getLegendPosition(m2t, handle, lStyle)
% handle legend location
% #COMPLEX: just a big switch-case
loc = get(handle, 'Location');
dist = 0.03; % distance to to axes in normalized coordinates
% MATLAB(R)'s keywords are camel cased (e.g., 'NorthOutside'), in Octave
% small cased ('northoutside'). Hence, use lower() for uniformity.
switch lower(loc)
case 'northeast'
return % don't do anything in this (default) case
case 'northwest'
position = [dist, 1-dist];
anchor = 'north west';
case 'southwest'
position = [dist, dist];
anchor = 'south west';
case 'southeast'
position = [1-dist, dist];
anchor = 'south east';
case 'north'
position = [0.5, 1-dist];
anchor = 'north';
case 'east'
position = [1-dist, 0.5];
anchor = 'east';
case 'south'
position = [0.5, dist];
anchor = 'south';
case 'west'
position = [dist, 0.5];
anchor = 'west';
case 'northoutside'
position = [0.5, 1+dist];
anchor = 'south';
case 'southoutside'
position = [0.5, -dist];
anchor = 'north';
case 'eastoutside'
position = [1+dist, 0.5];
anchor = 'west';
case 'westoutside'
position = [-dist, 0.5];
anchor = 'east';
case 'northeastoutside'
position = [1+dist, 1];
anchor = 'north west';
case 'northwestoutside'
position = [-dist, 1];
anchor = 'north east';
case 'southeastoutside'
position = [1+dist, 0];
anchor = 'south west';
case 'southwestoutside'
position = [-dist, 0];
anchor = 'south east';
case 'none'
legendPos = get(handle, 'Position');
unit = get(handle, 'Units');
if isequal(unit, 'normalized')
position = legendPos(1:2);
else
% Calculate where the legend is located w.r.t. the axes.
axesPos = get(m2t.current.gca, 'Position');
axesUnit = get(m2t.current.gca, 'Units');
% Convert to legend unit
axesPos = convertUnits(axesPos, axesUnit, unit);
% By default, the axes position is given w.r.t. to the figure,
% and so is the legend.
position = (legendPos(1:2)-axesPos(1:2)) ./ axesPos(3:4);
end
anchor = 'south west';
case {'best','bestoutside'}
% TODO: Implement these.
% The position could be determined by means of 'Position' and/or
% 'OuterPosition' of the legend handle; in fact, this could be made
% a general principle for all legend placements.
userWarning(m2t, [sprintf(' Option ''%s'' not yet implemented.',loc), ...
' Choosing default.']);
return % use defaults
otherwise
userWarning(m2t, [' Unknown legend location ''',loc,'''' ...
'. Choosing default.']);
return % use defaults
end
% set legend position
%TODO: shouldn't this include units?
lStyle = opts_add(lStyle, 'at', sprintf('{(%s,%s)}', ...
formatDim(position(1)), formatDim(position(2))));
lStyle = opts_add(lStyle, 'anchor', anchor);
end
% ==============================================================================
function [lStyle] = getLegendEntryAlignment(m2t, handle, lStyle)
% determines the text and picture alignment inside a legend
textalign = '';
pictalign = '';
switch getEnvironment
case 'Octave'
% Octave allows to change the alignment of legend text and
% pictograms using legend('left') and legend('right')
textpos = get(handle, 'textposition');
switch lower(textpos)
case 'left'
% pictogram right of flush right text
textalign = 'right';
pictalign = 'right';
case 'right'
% pictogram left of flush left text (default)
textalign = 'left';
pictalign = 'left';
otherwise
userWarning(m2t, ...
['Unknown legend text position ''',...
textpos, '''. Choosing default.']);
end
case 'MATLAB'
% does not specify text/pictogram alignment in legends
otherwise
errorUnknownEnvironment();
end
% set alignment of legend text and pictograms, if available
if ~isempty(textalign) && ~isempty(pictalign)
lStyle = opts_add(lStyle, 'legend cell align', textalign);
lStyle = opts_add(lStyle, 'align', textalign);
lStyle = opts_add(lStyle, 'legend plot pos', pictalign);
else
% Make sure the entries are flush left (default MATLAB behavior).
% This is also import for multiline legend entries: Without alignment
% specification, the TeX document won't compile.
% 'legend plot pos' is not set explicitly, since 'left' is default.
lStyle = opts_add(lStyle, 'legend cell align', 'left');
lStyle = opts_add(lStyle, 'align', 'left');
end
end
% ==============================================================================
function [pTicks, pTickLabels] = ...
matlabTicks2pgfplotsTicks(m2t, ticks, tickLabels, isLogAxis, tickLabelMode)
% Converts MATLAB style ticks and tick labels to pgfplots style (if needed)
if isempty(ticks)
pTicks = '\empty';
pTickLabels = [];
return
end
% set ticks + labels
pTicks = join(m2t, num2cell(ticks), ',');
% if there's no specific labels, return empty
if isempty(tickLabels) || (length(tickLabels)==1 && isempty(tickLabels{1}))
pTickLabels = '\empty';
return
end
% sometimes tickLabels are cells, sometimes plain arrays
% -- unify this to cells
if ischar(tickLabels)
tickLabels = strtrim(mat2cell(tickLabels, ...
ones(size(tickLabels,1), 1), ...
size(tickLabels, 2) ...
) ...
);
end
ticks = removeSuperfluousTicks(ticks, tickLabels);
isNeeded = isTickLabelsNecessary(m2t, ticks, tickLabels, isLogAxis);
pTickLabels = formatPgfTickLabels(m2t, isNeeded, tickLabels, ...
isLogAxis, tickLabelMode);
end
% ==============================================================================
function bool = isTickLabelsNecessary(m2t, ticks, tickLabels, isLogAxis)
% Check if tickLabels are really necessary (and not already covered by
% the tick values themselves).
bool = false;
k = find(ticks ~= 0.0, 1); % get an index with non-zero tick value
if isLogAxis || isempty(k) % only a 0-tick
scalingFactor = 1;
else
% When plotting axis, MATLAB might scale the axes by a factor of ten,
% say 10^n, and plot a 'x 10^k' next to the respective axis. This is
% common practice when the tick marks are really large or small
% numbers.
% Unfortunately, MATLAB doesn't contain the information about the
% scaling anywhere in the plot, and at the same time the {x,y}TickLabels
% are given as t*10^k, thus no longer corresponding to the actual
% value t.
% Try to find the scaling factor here. This is then used to check
% whether or not explicit {x,y}TickLabels are really necessary.
s = str2double(tickLabels{k});
scalingFactor = ticks(k)/s;
% check if the factor is indeed a power of 10
S = log10(scalingFactor);
if abs(round(S)-S) > m2t.tol
scalingFactor = 1.0;
end
end
for k = 1:min(length(ticks),length(tickLabels))
% Don't use str2num here as then, literal strings as 'pi' get
% legally transformed into 3.14... and the need for an explicit
% label will not be recognized. str2double returns a NaN for 'pi'.
if isLogAxis
s = 10^(str2double(tickLabels{k}));
else
s = str2double(tickLabels{k});
end
if isnan(s) || abs(ticks(k)-s*scalingFactor) > m2t.tol
bool = true;
return;
end
end
end
% ==============================================================================
function pTickLabels = formatPgfTickLabels(m2t, plotLabelsNecessary, ...
tickLabels, isLogAxis, tickLabelMode)
% formats the tick labels for pgfplots
if plotLabelsNecessary
for k = 1:length(tickLabels)
% Turn tickLabels from cells containing a cell into
% cells containing strings
if isnumeric(tickLabels{k})
tickLabels(k) = num2str(tickLabels{k});
elseif iscell(tickLabels{k})
tickLabels(k) = tickLabels{k};
end
% If the axis is logscaled, MATLAB does not store the labels,
% but the exponents to 10
if isLogAxis && strcmpi(tickLabelMode,'auto')
tickLabels{k} = sprintf('$10^{%s}$', str);
end
end
tickLabels = cellfun(@(l)(sprintf('{%s}',l)), tickLabels, ...
'UniformOutput', false);
pTickLabels = join(m2t, tickLabels, ',');
else
pTickLabels = [];
end
end
% ==============================================================================
function ticks = removeSuperfluousTicks(ticks, tickLabels)
% What MATLAB does when the number of ticks and tick labels is not the same,
% is somewhat unclear. Cut of the first entries to fix bug
% https://github.com/matlab2tikz/matlab2tikz/issues/161,
m = length(ticks);
n = length(tickLabels);
if n < m
ticks = ticks(m-n+1:end);
end
end
% ==============================================================================
function tikzLineStyle = translateLineStyle(matlabLineStyle)
if(~ischar(matlabLineStyle))
error('matlab2tikz:translateLineStyle:NotAString',...
'Variable matlabLineStyle is not a string.');
end
switch (matlabLineStyle)
case 'none'
tikzLineStyle = '';
case '-'
tikzLineStyle = 'solid';
case '--'
tikzLineStyle = 'dashed';
case ':'
tikzLineStyle = 'dotted';
case '-.'
tikzLineStyle = 'dashdotted';
otherwise
error('matlab2tikz:translateLineStyle:UnknownLineStyle',...
'Unknown matlabLineStyle ''%s''.', matlabLineStyle);
end
end
% ==============================================================================
function [m2t, table, opts] = makeTable(m2t, varargin)
% [m2t,table,opts] = makeTable(m2t, 'name1', data1, 'name2', data2, ...)
% [m2t,table,opts] = makeTable(m2t, {'name1','name2',...}, {data1, data2, ...})
% [m2t,table,opts] = makeTable(m2t, {'name1','name2',...}, [data1(:), data2(:), ...])
%
% Returns m2t structure, formatted table and table options.
% When all the names are empty, no header is printed
[variables, data] = parseInputsForTable_(varargin{:});
opts = opts_new();
COLSEP = sprintf('\t');
if m2t.args.externalData
ROWSEP = sprintf('\n');
else
ROWSEP = sprintf('\\\\\n');
opts = opts_add(opts, 'row sep','crcr');
end
nColumns = numel(data);
nRows = cellfun(@numel, data);
if ~all(nRows==nRows(1))
error('matlab2tikz:makeTableDifferentNumberOfRows',...
'Different data lengths [%s].', num2str(nRows));
end
nRows = nRows(1);
FORMAT = repmat({m2t.ff}, 1, nColumns);
FORMAT(cellfun(@isCellOrChar, data)) = {'%s'};
FORMAT = join(m2t, FORMAT, COLSEP);
if all(cellfun(@isempty, variables))
header = {};
else
header = {join(m2t, variables, COLSEP)};
end
table = cell(nRows,1);
for iRow = 1:nRows
thisData = cell(1,nColumns);
for jCol = 1:nColumns
thisData{1,jCol} = data{jCol}(iRow);
end
table{iRow} = sprintf(FORMAT, thisData{:});
end
table = lower(table); % convert NaN and Inf to lower case for TikZ
table = [join(m2t, [header;table], ROWSEP) ROWSEP];
if m2t.args.externalData
% output data to external file
[m2t, fileNum] = incrementGlobalCounter(m2t, 'tsvFile');
[filename, latexFilename] = externalFilename(m2t, fileNum, '.tsv');
% write the data table to an external file
fid = fileOpenForWrite(m2t, filename);
finally_fclose_fid = onCleanup(@() fclose(fid));
fprintf(fid, '%s', table);
% put the filename in the TikZ output
table = latexFilename;
else
% output data with "%newline" prepended for formatting consistency
% do NOT prepend another newline in the output: LaTeX will crash.
table = sprintf('%%\n%s', table);
end
end
% ==============================================================================
function [variables, data] = parseInputsForTable_(varargin)
% parse input arguments for |makeTable|
if numel(varargin) == 2 % cell syntax
variables = varargin{1};
data = varargin{2};
if ischar(variables)
% one variable, one data vector -> (cell, cell)
variables = {variables};
data = {data};
elseif iscellstr(variables) && ~iscell(data)
% multiple variables, one data matrix -> (cell, cell) by column
data = num2cell(data, 1);
end
else % key-value syntax
variables = varargin(1:2:end-1);
data = varargin(2:2:end);
end
end
% ==============================================================================
function [path, texpath] = externalFilename(m2t, counter, extension)
% generates a file name for an external data file and its relative TeX path
[dummy, name] = fileparts(m2t.tikzFileName); %#ok
baseFilename = [name '-' num2str(counter) extension];
path = fullfile(m2t.dataPath, baseFilename);
texpath = TeXpath(fullfile(m2t.relativeDataPath, baseFilename));
end
% ==============================================================================
function [names,definitions] = dealColorDefinitions(mergedColorDefs)
if isempty(mergedColorDefs)
mergedColorDefs = {};
end
[names,definitions] = cellfun(@(x)(deal(x{:})), mergedColorDefs, ...
'UniformOutput', false);
end
% ==============================================================================
function [m2t, colorLiteral] = rgb2colorliteral(m2t, rgb)
% Translates an rgb value to an xcolor literal
%
% Possible outputs:
% - xcolor literal color, e.g. 'blue'
% - mixture of 2 previously defined colors, e.g. 'red!70!green'
% - a newly defined color, e.g. 'mycolor10'
% Take a look at xcolor.sty for the color definitions.
% In xcolor.sty some colors are defined in CMYK space and approximated
% crudely for RGB color space. So it is better to redefine those colors
% instead of using xcolor's:
% 'cyan' , 'magenta', 'yellow', 'olive'
% [0,1,1], [1,0,1] , [1,1,0] , [0.5,0.5,0]
xcolColorNames = {'white', 'black', 'red', 'green', 'blue', ...
'brown', 'lime', 'orange', 'pink', ...
'purple', 'teal', 'violet', ...
'darkgray', 'gray', 'lightgray'};
xcolColorSpecs = {[1,1,1], [0,0,0], [1,0,0], [0,1,0], [0,0,1], ...
[0.75,0.5,0.25], [0.75,1,0], [1,0.5,0], [1,0.75,0.75], ...
[0.75,0,0.25], [0,0.5,0.5], [0.5,0,0.5], ...
[0.25,0.25,0.25], [0.5,0.5,0.5], [0.75,0.75,0.75]};
colorNames = [xcolColorNames, m2t.color.extraNames];
colorSpecs = [xcolColorSpecs, m2t.color.extraSpecs];
%% check if rgb is a predefined color
for kColor = 1:length(colorSpecs)
Ck = colorSpecs{kColor}(:);
if max(abs(Ck - rgb(:))) < m2t.color.precision
colorLiteral = colorNames{kColor};
return % exact color was predefined
end
end
%% check if the color is a linear combination of two already defined colors
for iColor = 1:length(colorSpecs)
for jColor = iColor+1:length(colorSpecs)
Ci = colorSpecs{iColor}(:);
Cj = colorSpecs{jColor}(:);
% solve color mixing equation `Ck = p * Ci + (1-p) * Cj` for p
p = (Ci-Cj) \ (rgb(:)-Cj);
p = round(100*p)/100; % round to a percentage
Ck = p * Ci + (1-p)*Cj; % approximated mixed color
if p <= 1 && p >= 0 && max(abs(Ck(:) - rgb(:))) < m2t.color.precision
colorLiteral = sprintf('%s!%d!%s', colorNames{iColor}, round(p*100), ...
colorNames{jColor});
return % linear combination found
end
end
end
%% Define colors that are not a linear combination of two known colors
colorLiteral = sprintf('mycolor%d', length(m2t.color.extraNames)+1);
m2t.color.extraNames{end+1} = colorLiteral;
m2t.color.extraSpecs{end+1} = rgb;
end
% ==============================================================================
function newstr = join(m2t, cellstr, delimiter)
% This function joins a cell of strings to a single string (with a
% given delimiter in between two strings, if desired).
%
% Example of usage:
% join(m2t, cellstr, ',')
newstr = m2tstrjoin(cellstr, delimiter, m2t.ff);
end
% ==============================================================================
function [width, height, unit] = getNaturalFigureDimension(m2t)
% Returns the size of figure (in inch)
% To stay compatible with getNaturalAxesDimensions, the unit 'in' is
% also returned.
% Get current figure size
figuresize = get(m2t.current.gcf, 'Position');
figuresize = figuresize([3 4]);
figureunit = get(m2t.current.gcf, 'Units');
% Convert Figure Size
unit = 'in';
figuresize = convertUnits(figuresize, figureunit, unit);
% Split size into width and height
width = figuresize(1);
height = figuresize(2);
end
% ==============================================================================
function dimension = getFigureDimensions(m2t, widthString, heightString)
% Returns the physical dimension of the figure.
[width, height, unit] = getNaturalFigureDimension(m2t);
% get the natural width-height ration of the plot
axesWidthHeightRatio = width / height;
% check matlab2tikz arguments
if ~isempty(widthString)
width = extractValueUnit(widthString);
end
if ~isempty(heightString)
height = extractValueUnit(heightString);
end
% prepare the output
if ~isempty(widthString) && ~isempty(heightString)
dimension.x.unit = width.unit;
dimension.x.value = width.value;
dimension.y.unit = height.unit;
dimension.y.value = height.value;
elseif ~isempty(widthString)
dimension.x.unit = width.unit;
dimension.x.value = width.value;
dimension.y.unit = width.unit;
dimension.y.value = width.value / axesWidthHeightRatio;
elseif ~isempty(heightString)
dimension.y.unit = height.unit;
dimension.y.value = height.value;
dimension.x.unit = height.unit;
dimension.x.value = height.value * axesWidthHeightRatio;
else % neither width nor height given
dimension.x.unit = unit;
dimension.x.value = width;
dimension.y.unit = unit;
dimension.y.value = height;
end
end
% ==============================================================================
function position = getAxesPosition(m2t, handle, widthString, heightString, axesBoundingBox)
% Returns the physical position of the axes. This includes - in difference
% to the Dimension - also an offset to shift the axes inside the figure
% An optional bounding box can be used to omit empty borders.
% Deal with optional parameter
if nargin < 4
axesBoundingBox = [0 0 1 1];
end
% First get the whole figures size
figDim = getFigureDimensions(m2t, widthString, heightString);
% Get the relative position of the axis
relPos = getRelativeAxesPosition(m2t, handle, axesBoundingBox);
position.x.value = relPos(1) * figDim.x.value;
position.x.unit = figDim.x.unit;
position.y.value = relPos(2) * figDim.y.value;
position.y.unit = figDim.y.unit;
position.w.value = relPos(3) * figDim.x.value;
position.w.unit = figDim.x.unit;
position.h.value = relPos(4) * figDim.y.value;
position.h.unit = figDim.y.unit;
end
% ==============================================================================
function [position] = getRelativeAxesPosition(m2t, axesHandles, axesBoundingBox)
% Returns the relative position of axes within the figure.
% Position is an (n,4) matrix with [minX, minY, width, height] for each
% handle. All these values are relative to the figure size, which means
% that [0, 0, 1, 1] covers the whole figure.
% It is possible to add a second parameter with the relative coordinates of
% a bounding box around all axes of the figure (see getRelevantAxes()). In
% this case, relative positions are rescaled so that the bounding box is
% [0, 0, 1, 1]
% Get Figure Dimension
[figWidth, figHeight, figUnits] = getNaturalFigureDimension(m2t);
% Initialize position
position = zeros(numel(axesHandles), 4);
% Iterate over all handles
for i = 1:numel(axesHandles)
axesHandle = axesHandles(i);
axesPos = get(axesHandle, 'Position');
axesUnits = get(axesHandle, 'Units');
if isequal(lower(axesUnits), 'normalized')
% Position is already relative
position(i,:) = axesPos;
else
% Convert figure size into axes units
figureSize = convertUnits([figWidth, figHeight], figUnits, axesUnits);
% Figure size into axes units to get the relative size
position(i,:) = axesPos ./ [figureSize, figureSize];
end
if strcmpi(get(axesHandle, 'DataAspectRatioMode'), 'manual') ...
|| strcmpi(get(axesHandle, 'PlotBoxAspectRatioMode'), 'manual')
if strcmpi(get(axesHandle,'Projection'),'Perspective')
userWarning(m2t,'Perspective projections are not currently supported')
end
% project vertices of 3d plot box (this results in 2d coordinates in
% an absolute coordinate system that is scaled proportionally by
% Matlab to fit the axes position box)
switch getEnvironment()
case 'MATLAB'
projection = view(axesHandle);
case 'Octave'
% Unfortunately, Octave does not have the full `view`
% interface implemented, but the projection matrices are
% available: http://octave.1599824.n4.nabble.com/Implementing-view-td3032041.html
projection = get(axesHandle, 'x_viewtransform');
otherwise
errorUnknownEnvironment();
end
vertices = projection * [0, 1, 0, 0, 1, 1, 0, 1;
0, 0, 1, 0, 1, 0, 1, 1;
0, 0, 0, 1, 0, 1, 1, 1;
1, 1, 1, 1, 1, 1, 1, 1];
% each of the columns of vertices represents a vertex of the 3D axes
% but we only need their XY coordinates
verticesXY = vertices([1 2], :);
% the size of the projected plot box is limited by the long diagonals
% The matrix A determines the connectivity, e.g. the first diagonal runs from vertices(:,3) -> vertices(:,4)
A = [ 0, 0, 0, -1, +1, 0, 0, 0;
0, 0, -1, 0, 0, +1, 0, 0;
0, -1, 0, 0, 0, 0, +1, 0;
-1, 0, 0, 0, 0, 0, 0, +1];
diagonals = verticesXY * A';
% each of the columns of this matrix contains a the X and Y distance of a diagonal
dimensions = max(abs(diagonals), [], 2);
% find limiting dimension and adjust position
aspectRatio = dimensions(2) * figWidth / (dimensions(1) * figHeight);
axesAspectRatio = position(i,4) / position(i,3);
if aspectRatio > axesAspectRatio
newWidth = position(i,4) / aspectRatio;
% Center Axis
offset = (position(i,3) - newWidth) / 2;
position(i,1) = position(i,1) + offset;
% Store new width
position(i,3) = newWidth;
else
newHeight = position(i,3) * aspectRatio;
offset = (position(i,4) - newHeight) / 2;
position(i,2) = position(i,2) + offset;
% Store new height
position(i,4) = newHeight;
end
end
end
%% Rescale if axesBoundingBox is given
if exist('axesBoundingBox','var')
% shift position so that [0, 0] is the lower left corner of the
% bounding box
position(:,1) = position(:,1) - axesBoundingBox(1);
position(:,2) = position(:,2) - axesBoundingBox(2);
% Recale
position(:,[1 3]) = position(:,[1 3]) / max(axesBoundingBox([3 4]));
position(:,[2 4]) = position(:,[2 4]) / max(axesBoundingBox([3 4]));
end
end
% ==============================================================================
function aspectRatio = getPlotBoxAspectRatio(axesHandle)
limits = axis(axesHandle);
if any(isinf(limits))
aspectRatio = get(axesHandle,'PlotBoxAspectRatio');
else
% DataAspectRatio has priority
dataAspectRatio = get(axesHandle,'DataAspectRatio');
nlimits = length(limits)/2;
limits = reshape(limits, 2, nlimits);
aspectRatio = abs(limits(2,:) - limits(1,:))./dataAspectRatio(1:nlimits);
aspectRatio = aspectRatio/min(aspectRatio);
end
end
% ==============================================================================
function texUnits = matlab2texUnits(matlabUnits, fallbackValue)
switch matlabUnits
case 'pixels'
texUnits = 'px'; % only in pdfTex/LuaTeX
case 'centimeters'
texUnits = 'cm';
case 'characters'
texUnits = 'em';
case 'points'
texUnits = 'pt';
case 'inches'
texUnits = 'in';
otherwise
texUnits = fallbackValue;
end
end
% ==============================================================================
function dstValue = convertUnits(srcValue, srcUnit, dstUnit)
% Converts values between different units.
% srcValue stores a length (or vector of lengths) in srcUnit.
% The resulting dstValue is the converted length into dstUnit.
%
% Currently supported units are: in, cm, px, pt
% Use tex units, if possible (to make things simple)
srcUnit = matlab2texUnits(lower(srcUnit),lower(srcUnit));
dstUnit = matlab2texUnits(lower(dstUnit),lower(dstUnit));
if isequal(srcUnit, dstUnit)
dstValue = srcValue;
return % conversion to the same unit => factor = 1
end
units = {srcUnit, dstUnit};
factor = ones(1,2);
for ii = 1:numel(factor) % Same code for srcUnit and dstUnit
% Use inches as intermediate unit
% Compute the factor to convert an inch into another unit
switch units{ii}
case 'cm'
factor(ii) = 2.54;
case 'px'
factor(ii) = get(0, 'ScreenPixelsPerInch');
case 'in'
factor(ii) = 1;
case 'pt'
factor(ii) = 72;
otherwise
warning('MATLAB2TIKZ:UnknownPhysicalUnit',...
'Can not convert unit ''%s''. Using conversion factor 1.', units{ii});
end
end
dstValue = srcValue * factor(2) / factor(1);
end
% ==============================================================================
function out = extractValueUnit(str)
% Decompose m2t.args.width into value and unit.
% Regular expression to match '4.12cm', '\figurewidth', ...
fp_regex = '[-+]?\d*\.?\d*(?:e[-+]?\d+)?';
pattern = strcat('(', fp_regex, ')?', '(\\?[a-zA-Z]+)');
[dummy,dummy,dummy,dummy,t,dummy] = regexp(str, pattern, 'match'); %#ok
if length(t)~=1
error('getAxesDimensions:illegalLength', ...
'The width string ''%s'' could not be decomposed into value-unit pair.', str);
end
if length(t{1}) == 1
out.value = 1.0; % such as in '1.0\figurewidth'
out.unit = strtrim(t{1}{1});
elseif length(t{1}) == 2 && isempty(t{1}{1})
% MATLAB(R) does this:
% length(t{1})==2 always, but the first field may be empty.
out.value = 1.0;
out.unit = strtrim(t{1}{2});
elseif length(t{1}) == 2
out.value = str2double(t{1}{1});
out.unit = strtrim(t{1}{2});
else
error('getAxesDimensions:illegalLength', ...
'The width string ''%s'' could not be decomposed into value-unit pair.', str);
end
end
% ==============================================================================
function str = escapeCharacters(str)
% Replaces "%" and "\" with respectively "%%" and "\\"
str = strrep(str, '%' , '%%');
str = strrep(str, '\' , '\\');
end
% ==============================================================================
function bool = isNone(value)
% Checks whether a value is 'none'
bool = strcmpi(value, 'none');
end
% ==============================================================================
function bool = isOn(value)
% Checks whether a value is 'on'
bool = strcmpi(value, 'on');
end
% ==============================================================================
function bool = isOff(value)
% Checks whether a value is 'off'.
% Note that some options are not be solely an on/off boolean, such that `isOn`
% and isOff don't always return the complement of each other and such that we
% need both functions to check the value.
% E.g. `set(0, 'HandleVisibility')` allows the value 'callback'.
bool = strcmpi(value, 'off');
end
% ==============================================================================
function val = getOrDefault(handle, key, default)
% gets the value or returns the default value if no such property exists
if all(isprop(handle, key))
val = get(handle, key);
else
val = default;
end
end
% ==============================================================================
function val = getFactoryOrDefault(type, key, fallback)
% get factory default value for a certain type of HG object
% this CANNOT be done using |getOrDefault| as |isprop| doesn't work for
% factory/default settings. Hence, we use a more expensive try-catch instead.
try
groot = 0;
val = get(groot, ['Factory' type key]);
catch
val = fallback;
end
end
% ==============================================================================
function [val, isDefault] = getAndCheckDefault(type, handle, key, default)
% gets the value from a handle of certain type and check the default values
default = getFactoryOrDefault(type, key, default);
val = getOrDefault(handle, key, default);
isDefault = isequal(val, default);
end
% ==============================================================================
function bool = isVisible(handles)
% Determines whether an object is actually visible or not.
bool = isOn(get(handles,'Visible'));
% There's another handle property, 'HandleVisibility', that is unrelated
% to the "physical" visibility of an object. Rather, it sets whether an
% object should be visitable by |findobj|. Hence, it is often switched off
% for non-data objects such as custom axes/grid objects.
end
% ==============================================================================
function [m2t, axesBoundingBox] = getRelevantAxes(m2t, axesHandles)
% Returns relevant axes. These are defines as visible axes that are no
% colorbars. Function 'findPlotAxes()' ensures that 'axesHandles' does not
% contain colorbars. In addition, a bounding box around all relevant Axes is
% computed. This can be used to avoid undesired borders.
% This function is the remaining code of alignSubPlots() in the alternative
% positioning system.
% List only visible axes
N = numel(axesHandles);
idx = false(N,1);
for ii = 1:N
idx(ii) = isVisibleContainer(axesHandles(ii));
end
% Store the relevant axes in m2t to simplify querying e.g. positions
% of subplots
m2t.relevantAxesHandles = axesHandles(idx);
% Compute the bounding box if width or height of the figure are set by
% parameter
if ~isempty(m2t.args.width) || ~isempty(m2t.args.height)
% TODO: check if relevant Axes or all Axes are better.
axesBoundingBox = getRelativeAxesPosition(m2t, m2t.relevantAxesHandles);
% Compute second corner from width and height for each axes
axesBoundingBox(:,[3 4]) = axesBoundingBox(:,[1 2]) + axesBoundingBox(:,[3 4]);
% Combine axes corners to get the bounding box
axesBoundingBox = [min(axesBoundingBox(:,[1 2]),[],1), max(axesBoundingBox(:,[3 4]), [], 1)];
% Compute width and height of the bounding box
axesBoundingBox(:,[3 4]) = axesBoundingBox(:,[3 4]) - axesBoundingBox(:,[1 2]);
else
% Otherwise take the whole figure as bounding box => lengths are
% not changed in tikz
axesBoundingBox = [0, 0, 1, 1];
end
end
% ==============================================================================
function userInfo(m2t, message, varargin)
% Display usage information.
if m2t.args.showInfo
mess = sprintf(message, varargin{:});
mess = strrep(mess, sprintf('\n'), sprintf('\n *** '));
fprintf(' *** %s\n', mess);
end
end
% ==============================================================================
function userWarning(m2t, message, varargin)
% Drop-in replacement for warning().
if m2t.args.showWarnings
warning('matlab2tikz:userWarning', message, varargin{:});
end
end
% ==============================================================================
function signalDependency(m2t, dependencyType, name)
% Signals an (optional) dependency to the user
switch lower(dependencyType)
case 'tikzlibrary'
message = 'Make sure to add "\\usetikzlibrary{%s}" to the preamble.';
otherwise
message = 'Please make sure to load the "%s" dependency';
end
userInfo(m2t, message, name);
end
% ==============================================================================
function warnAboutParameter(m2t, parameter, isActive, message)
% warn the user about the use of a dangerous parameter
line = ['\n' repmat('=',1,80) '\n'];
if isActive(m2t.args.(parameter))
userWarning(m2t, [line, 'You are using the "%s" parameter.\n', ...
message line], parameter);
end
end
% ==============================================================================
function parent = addChildren(parent, children)
if isempty(children)
return;
elseif iscell(children)
for k = 1:length(children)
parent = addChildren(parent, children{k});
end
else
if isempty(parent.children)
parent.children = {children};
else
parent.children = [parent.children children];
end
end
end
% ==============================================================================
function printAll(m2t, env, fid)
if isfield(env, 'colors') && ~isempty(env.colors)
fprintf(fid, '%s', env.colors);
end
if isempty(env.options)
fprintf(fid, '\\begin{%s}\n', env.name);
else
fprintf(fid, '\\begin{%s}[%%\n%s\n]\n', env.name, ...
opts_print(env.options, sprintf(',\n')));
end
for item = env.content
fprintf(fid, '%s', char(item));
end
for k = 1:length(env.children)
if ischar(env.children{k})
fprintf(fid, escapeCharacters(env.children{k}));
else
fprintf(fid, '\n');
printAll(m2t, env.children{k}, fid);
end
end
% End the tikzpicture environment with an empty comment and no newline
% so no additional space is generated after the tikzpicture in TeX.
if strcmp(env.name, 'tikzpicture') % LaTeX is case sensitive
fprintf(fid, '\\end{%s}%%', env.name);
else
fprintf(fid, '\\end{%s}\n', env.name);
end
end
% ==============================================================================
function c = prettyPrint(m2t, strings, interpreter)
% Some resources on how MATLAB handles rich (TeX) markup:
% http://www.mathworks.com/help/techdoc/ref/text_props.html#String
% http://www.mathworks.com/help/techdoc/creating_plots/f0-4741.html#f0-28104
% http://www.mathworks.com/help/techdoc/ref/text_props.html#Interpreter
% http://www.mathworks.com/help/techdoc/ref/text.html#f68-481120
% If the user set the matlab2tikz parameter 'parseStrings' to false, no
% parsing of strings takes place, thus making the user 100% responsible.
if ~m2t.args.parseStrings
% If strings is an actual string (labels etc) we need to return a
% cell containing the string
c = cellstr(strings);
return
end
% Make sure we have a valid interpreter set up
if ~any(strcmpi(interpreter, {'latex', 'tex', 'none'}))
userWarning(m2t, 'Don''t know interpreter ''%s''. Default handling.', interpreter);
interpreter = 'tex';
end
strings = cellstrOneLinePerCell(strings);
% Now loop over the strings and return them pretty-printed in c.
c = cell(1, length(strings));
for k = 1:length(strings)
% linear indexing for independence of cell array dimensions
s = strings{k};
% The interpreter property of the text element defines how the string
% is parsed
switch lower(interpreter)
case 'latex' % Basic subset of the LaTeX markup language
% Replace $$...$$ with $...$ for groups, but otherwise leave
% untouched.
% Displaymath \[...\] seems to be unsupported by TikZ/PGF.
% If this changes, use '\\[$2\\]' as replacement below.
% Do not escape dollar in replacement string (e.g., "\$$2\$"),
% since this is not properly handled by octave 3.8.2.
string = regexprep(s, '(\$\$)(.*?)(\$\$)', '$$2$');
case 'tex' % Subset of plain TeX markup language
% Deal with UTF8 characters.
string = s;
% degree symbol following "^" or "_" needs to be escaped
string = regexprep(string, '([\^\_])°', '$1{{}^\\circ}');
string = strrep(string, '°', '^\circ');
string = strrep(string, '∞', '\infty');
% Parse string piece-wise in a separate function.
string = parseTexString(m2t, string);
case 'none' % Literal characters
% Make special characters TeX compatible
string = strrep(s, '\', '\textbackslash{}');
% Note: '{' and '}' can't be converted to '\{' and '\}',
% respectively, via strrep(...) as this would lead to
% backslashes converted to '\textbackslash\{\}' because
% the backslash was converted to '\textbackslash{}' in
% the previous step. Using regular expressions with
% negative look-behind makes sure any braces in 'string'
% were not introduced by escaped backslashes.
% Also keep in mind that escaping braces before backslashes
% would not remedy the issue -- in that case 'string' would
% contain backslashes introduced by brace escaping that are
% not supposed to be printable characters.
repl = switchMatOct('\\{', '\{');
string = regexprep(string, '(?<!\\textbackslash){', repl);
repl = switchMatOct('\\}', '\}');
string = regexprep(string, '(?<!\\textbackslash{)}', repl);
string = strrep(string, '$', '\$');
string = strrep(string, '%', '\%');
string = strrep(string, '_', '\_');
string = strrep(string, '^', '\textasciicircum{}');
string = strrep(string, '#', '\#');
string = strrep(string, '&', '\&');
string = strrep(string, '~', '\textasciitilde{}'); % or '\~{}'
% Clean up: remove superfluous '{}' if it's followed by a backslash
string = strrep(string, '{}\', '\');
% Clean up: remove superfluous '{}' at the end of 'string'
string = regexprep(string, '\{\}$', '');
% Make sure to return a string and not a cellstr.
if iscellstr(string)
string = string{1};
end
otherwise
error('matlab2tikz:prettyPrint', 'Unknown interpreter');
end
c{k} = string;
end
end
% ==============================================================================
function strings = cellstrOneLinePerCell(strings)
% convert to cellstr that contains only one-line strings
if ischar(strings)
strings = cellstr(strings);
elseif iscellstr(strings)
cs = cell(1, length(strings));
for s = 1:length(strings)
tmp = cellstr(strings{s});
cs{s} = tmp;
end
strings = cs;
else
error('matlab2tikz:cellstrOneLinePerCell', ...
'Data type not understood.');
end
end
% ==============================================================================
function parsed = parseTexString(m2t, string)
if iscellstr(string)
% Convert cell string to regular string, otherwise MATLAB complains
string = string{:};
end
% Get the position of all braces
bracesPos = regexp(string, '\{|\}');
% Exclude braces that are part of any of these MATLAB-supported TeX commands:
% \color{...} \color[...]{...} \fontname{...} \fontsize{...}
[sCmd, eCmd] = regexp(string, '\\(color(\[[^\]]*\])?|fontname|fontsize)\{[^}]*\}');
for i = 1:length(sCmd)
bracesPos(bracesPos >= sCmd(i) & bracesPos <= eCmd(i)) = [];
end
% Exclude braces that are preceded by an odd number of backslashes which
% means the brace is escaped and thus to be printed, not a grouping brace
expr = '(?<!\\)(\\\\)*\\(\{|\})';
escaped = regexp(string, expr, 'end');
% It's necessary to go over 'string' with the same RegEx again to catch
% overlapping matches, e.g. string == '\{\}'. In such a case the simple
% regexp(...) above only finds the first brace. What we have to do is look
% only at the part of 'string' that starts with the first brace but doesn't
% encompass its escaping backslash. Iterating over all previously found
% matches makes sure all overlapping matches are found, too. That way even
% cases like string == '\{\} \{\}' are handled correctly.
% The call to unique(...) is not necessary to get the behavior described, but
% by removing duplicates in 'escaped' it's cleaner than without.
for i = escaped
escaped = unique([escaped, regexp(string(i:end), expr, 'end') + i-1]);
end
% Now do the actual removal of escaped braces
for i = 1:length(escaped)
bracesPos(bracesPos == escaped(i)) = [];
end
parsed = '';
% Have a virtual brace one character left of where the actual string
% begins (remember, MATLAB strings start counting at 1, not 0). This is
% to make sure substrings left of the first brace get parsed, too.
prevBracePos = 0;
% Iterate over all the brace positions in order to split up 'string'
% at those positions and then parse the substrings. A virtual brace is
% added right of where the actual string ends to make sure substrings
% right of the right-most brace get parsed as well.
for currBracePos = [bracesPos, length(string)+1]
if (prevBracePos + 1) < currBracePos
% Parse the substring between (but not including) prevBracePos
% and currBracePos, i.e. between the previous brace and the
% current one (but only if there actually is a non-empty
% substring). Then append it to the output string.
substring = string(prevBracePos+1 : currBracePos-1);
parsed = [parsed, parseTexSubstring(m2t, substring)];
end
if currBracePos <= length(string)
% Append the brace itself to the output string, but only if the
% current brace position is within the limits of the string, i.e.
% don't append anything for the last, virtual brace that is only
% there to enable parsing of substrings beyond the right-most
% actual brace.
brace = string(currBracePos);
parsed = [parsed, brace];
end
% The current brace position will be next iteration's previous one
prevBracePos = currBracePos;
end
% Enclose everything in $...$ to use math mode
parsed = ['$' parsed '$'];
% ...except when everything is text
parsed = regexprep(parsed, '^\$\\text\{([^}]*)\}\$$', '$1');
% start-> $ \text {(non-}) } $<-end
% ...or when the parsed string is empty
parsed = regexprep(parsed, '^\$\$$', '');
% Ensure math mode for pipe symbol (issue #587)
parsed = strrep(parsed, '|', '$|$');
end
% ==============================================================================
function string = parseTexSubstring(m2t, string)
origstr = string; % keep this for warning messages
% Font families (italic, bold, etc.) get a trailing '{}' because they may be
% followed by a letter which would produce an error in (La)TeX.
for i = {'it', 'bf', 'rm', 'sl'}
string = strrep(string, ['\' i{:}], ['\' i{:} '{}']);
end
% The same holds true for special characters like \alpha
% The list of MATLAB-supported TeX characters was taken from
% http://www.mathworks.com/help/techdoc/ref/text_props.html#String
named = {'alpha', 'angle', 'ast', 'beta', 'gamma', 'delta', ...
'epsilon', 'zeta', 'eta', 'theta', 'vartheta', 'iota', ...
'kappa', 'lambda', 'mu', 'nu', 'xi', 'pi', 'rho', ...
'sigma', 'varsigma', 'tau', 'equiv', 'Im', 'otimes', ...
'cap', 'int', 'rfloor', 'lfloor', 'perp', 'wedge', ...
'rceil', 'vee', 'langle', 'upsilon', 'phi', 'chi', ...
'psi', 'omega', 'Gamma', 'Delta', 'Theta', 'Lambda', ...
'Xi', 'Pi', 'Sigma', 'Upsilon', 'Phi', 'Psi', 'Omega', ...
'forall', 'exists', 'ni', 'cong', 'approx', 'Re', ...
'oplus', 'cup', 'subseteq', 'lceil', 'cdot', 'neg', ...
'times', 'surd', 'varpi', 'rangle', 'sim', 'leq', ...
'infty', 'clubsuit', 'diamondsuit', 'heartsuit', ...
'spadesuit', 'leftrightarrow', 'leftarrow', ...
'Leftarrow', 'uparrow', 'rightarrow', 'Rightarrow', ...
'downarrow', 'circ', 'pm', 'geq', 'propto', 'partial', ...
'bullet', 'div', 'neq', 'aleph', 'wp', 'oslash', ...
'supseteq', 'nabla', 'ldots', 'prime', '0', 'mid', ...
'copyright' };
for i = named
string = strrep(string, ['\' i{:}], ['\' i{:} '{}']);
% FIXME: Only append '{}' if there's an odd number of backslashes
% in front of the items from 'named'. If it's an even
% number instead, that means there's an escaped (printable)
% backslash and some text like "alpha" after that.
end
% Some special characters' names are subsets of others, e.g. '\o' is
% a subset of '\omega'. This would produce undesired double-escapes.
% For example if '\o' was converted to '\o{}' after '\omega' has been
% converted to '\omega{}' this would result in '\o{}mega{}' instead of
% '\omega{}'. Had '\o' been converted to '\o{}' _before_ '\omega' is
% converted then the result would be '\o{}mega' and thus also wrong.
% To circumvent the problem all those special character names that are
% subsets of others are now converted using a regular expression that
% uses negative lookahead. The special handling of the backslash is
% required for MATLAB/Octave compatibility.
string = regexprep(string, '(\\)o(?!mega|times|plus|slash)', '$1o{}');
string = regexprep(string, '(\\)in(?!t|fty)', '$1in{}');
string = regexprep(string, '(\\)subset(?!eq)', '$1subset{}');
string = regexprep(string, '(\\)supset(?!eq)', '$1supset{}');
% Convert '\0{}' (TeX text mode) to '\emptyset{}' (TeX math mode)
string = strrep(string, '\0{}', '\emptyset{}');
% Add skip to \fontsize
% This is required for a successful LaTeX run on the output as in contrast
% to MATLAB/Octave it requires the skip parameter (even if it's zero)
string = regexprep(string, '(\\fontsize\{[^}]*\})', '$1{0}');
% Put '\o{}' inside \text{...} as it is a text mode symbol that does not
% exist in math mode (and LaTeX gives a warning if you use it in math mode)
string = strrep(string, '\o{}', '\text{\o{}}');
% Put everything that isn't a TeX command inside \text{...}
expr = '(\\[a-zA-Z]+(\[[^\]]*\])?(\{[^}]*\}){1,2})';
% |( \cmd )( [...]? )( {...}{1,2} )|
% ( subset $1 )
repl = '}$1\\text{';
string = regexprep(string, expr, repl);
% ...\alpha{}... -> ...}\alpha{}\text{...
string = ['\text{' string '}'];
% ...}\alpha{}\text{... -> \text{...}\alpha{}\text{...}
% '_' has to be in math mode so long as it's not escaped as '\_' in which
% case it remains as-is. Extra care has to be taken to make sure any
% backslashes in front of the underscore are not themselves escaped and
% thus printable backslashes. This is the case if there's an even number
% of backslashes in a row.
repl = '$1}_\\text{';
string = regexprep(string, '(?<!\\)((\\\\)*)_', repl);
% '^' has to be in math mode so long as it's not escaped as '\^' in which
% case it is expressed as '\textasciicircum{}' for compatibility with
% regular TeX. Same thing here regarding even/odd number of backslashes
% as in the case of underscores above.
repl = '$1\\textasciicircum{}';
string = regexprep(string, '(?<!\\)((\\\\)*)\\\^', repl);
repl = '$1}^\\text{';
string = regexprep(string, '(?<!\\)((\\\\)*)\^', repl);
% '<' and '>' has to be either in math mode or needs to be typeset as
% '\textless' and '\textgreater' in textmode
% This is handled better, if 'parseStringsAsMath' is activated
if m2t.args.parseStringsAsMath == 0
string = regexprep(string, '<', '\\textless{}');
string = regexprep(string, '>', '\\textgreater{}');
end
% Move font styles like \bf into the \text{} command.
expr = '(\\bf|\\it|\\rm|\\fontname)({\w*})+(\\text{)';
while regexp(string, expr)
string = regexprep(string, expr, '$3$1$2');
end
% Replace Fontnames
[dummy, dummy, dummy, dummy, fonts, dummy, subStrings] = regexp(string, '\\fontname{(\w*)}'); %#ok
fonts = fonts2tex(fonts);
subStrings = [subStrings; fonts, {''}];
string = cell2mat(subStrings(:)');
% Merge adjacent \text fields:
string = mergeAdjacentTexCmds(string, '\text');
% '\\' has to be escaped to '\textbackslash{}'
% This cannot be done with strrep(...) as it would replace e.g. 4 backslashes
% with three times the replacement string because it finds overlapping matches
% (see http://www.mathworks.de/help/techdoc/ref/strrep.html)
% Note: Octave's backslash handling is broken. Even though its output does
% not resemble MATLAB's, the same m2t code is used for either software. That
% way MATLAB-compatible code produces the same matlab2tikz output no matter
% which software it's executed in. So long as this MATLAB incompatibility
% remains in Octave you're probably better off not using backslashes in TeX
% text anyway.
string = regexprep(string, '(\\)\\', '$1textbackslash{}');
% '_', '^', '{', and '}' are already escaped properly, even in MATLAB's TeX
% dialect (and if they're not, that's intentional)
% Escape "$", "%", and "#" to make them compatible to true TeX while in
% MATLAB/Octave they are not escaped
string = strrep(string, '$', '\$');
string = strrep(string, '%', '\%');
string = strrep(string, '#', '\#');
% Escape "§" as "\S" since it can give UTF-8 problems otherwise.
% The TeX string 'a_§' in particular lead to problems in Octave 3.6.0.
% m2t transcoded that string into '$\text{a}_\text{*}\text{#}$' with
% * = 0xC2 and # = 0xA7 which corresponds with the two-byte UTF-8
% encoding. Even though this looks like an Octave bug that shows
% during the '..._\text{abc}' to '..._\text{a}\text{bc}' conversion,
% it's best to include the workaround here.
string = strrep(string, '§', '\S{}');
string = escapeAmpersands(m2t, string, origstr);
string = escapeTildes(m2t, string, origstr);
% Convert '..._\text{abc}' and '...^\text{abc}' to '..._\text{a}\text{bc}'
% and '...^\text{a}\text{bc}', respectively.
% Things get a little more complicated if instead of 'a' it's e.g. '$'. The
% latter has been converted to '\$' by now and simply extracting the first
% character from '\text{\$bc}' would result in '\text{$}\text{$bc}' which
% is syntactically wrong. Instead the whole command '\$' has to be moved in
% front of the \text{...} block, e.g. '..._\text{\$bc}' -> '..._\$\text{bc}'.
% Note that the problem does not occur for the majority of special characters
% like '\alpha' because they use math mode and therefore are never inside a
% \text{...} block to begin with. This means that the number of special
% characters affected by this issue is actually quite small:
% $ # % & _ { } \o § ~ \ ^
expr = ['(_|\^)(\\text)\{([^}\\]|\\\$|\\#|\\%|\\&|\\_|\\\{|\\\}|', ...
... % (_/^)(\text) {(non-}\| \$ | \#| \%| \&| \_| \{ | \} |
... % ($1)( $2 ) ( $3 ->
'\\o\{\}|\\S\{\}|\\textasciitilde\{\}|\\textbackslash\{\}|', ...
... % \o{} | \S{} | \textasciitilde{} | \textbackslash{} |
... % <- $3 ->
'\\textasciicircum\{\})'];
% \textasciicircum{} )
% <- $3 )
string = regexprep(string, expr, '$1$2{$3}$2{');
string = parseStringsAsMath(m2t, string);
% Clean up: remove empty \text{}
string = strrep(string, '\text{}', '');
% \text{}\alpha{}\text{...} -> \alpha{}\text{...}
% Clean up: convert '{}\' to '\' unless it's prefixed by a backslash which
% means the opening brace is escaped and thus a printable character instead
% of a grouping brace.
string = regexprep(string, '(?<!\\)\{\}(\\)', '$1');
% \alpha{}\text{...} -> \alpha\text{...}
% Clean up: convert '{}}' to '}' unless it's prefixed by a backslash
string = regexprep(string, '(?<!\\)\{\}\}', '}');
% Clean up: remove '{}' at the end of 'string' unless it's prefixed by a
% backslash
string = regexprep(string, '(?<!\\)\{\}$', '');
end
% ==============================================================================
function string = escapeTildes(m2t, string, origstr)
% Escape plain "~" in MATLAB and replace escaped "\~" in Octave with a proper
% escape sequence. An un-escaped "~" produces weird output in Octave, thus
% give a warning in that case
switch getEnvironment
case 'MATLAB'
string = strrep(string, '~', '\textasciitilde{}'); % or '\~{}'
case 'Octave'
string = strrep(string, '\~', '\textasciitilde{}'); % ditto
if regexp(string, '(?<!\\)~')
userWarning(m2t, ...
['TeX string ''%s'' contains un-escaped ''~''. ' ...
'For proper display in Octave you probably ' ...
'want to escape it even though that''s ' ...
'incompatible with MATLAB. ' ...
'In the matlab2tikz output it will have its ' ...
'usual TeX function as a non-breaking space.'], ...
origstr)
end
otherwise
errorUnknownEnvironment();
end
end
% ==============================================================================
function string = escapeAmpersands(m2t, string, origstr)
% Escape plain "&" in MATLAB and replace it and the following character with
% a space in Octave unless the "&" is already escaped
switch getEnvironment
case 'MATLAB'
string = strrep(string, '&', '\&');
case 'Octave'
% Ampersands should already be escaped in Octave.
% Octave (tested with 3.6.0) handles un-escaped ampersands a little
% funny in that it removes the following character, if there is one:
% 'abc&def' -> 'abc ef'
% 'abc&\deltaef' -> 'abc ef'
% 'abc&$ef' -> 'abc ef'
% 'abcdef&' -> 'abcdef'
% Don't remove closing brace after '&' as this would result in
% unbalanced braces
string = regexprep(string, '(?<!\\)&(?!})', ' ');
string = regexprep(string, '(?<!\\)&}', '}');
if regexp(string, '(?<!\\)&\\')
% If there's a backslash after the ampersand, that means not only
% the backslash should be removed but the whole escape sequence,
% e.g. '\delta' or '\$'. Actually the '\delta' case is the
% trickier one since by now 'string' would have been turned from
% 'abc&\deltaef' into '\text{abc&}\delta{}\text{ef}', i.e. after
% the ampersand first comes a closing brace and then '\delta';
% the latter as well as the ampersand itself should be removed
% while the brace must remain in place to avoid unbalanced braces.
userWarning(m2t, ...
['TeX string ''%s'' contains a special character ' ...
'after an un-escaped ''&''. The output generated ' ...
'by matlab2tikz will not precisely match that ' ...
'which you see in Octave itself in that the ' ...
'special character and the preceding ''&'' is ' ...
'not replaced with a space.'], origstr)
end
otherwise
errorUnknownEnvironment();
end
end
% ==============================================================================
function [string] = parseStringsAsMath(m2t, string)
% Some further processing makes the output behave more like TeX math mode,
% but only if the matlab2tikz parameter parseStringsAsMath=true.
if m2t.args.parseStringsAsMath
% Some characters should be in math mode: =-+/,.()<>0-9
expr = '(\\text)\{([^}=\-+/,.()<>0-9]*)([=\-+/,.()<>0-9]+)([^}]*)\}';
% \text {(any non-"x"/'}'char)( any "x" char )(non-}) }
% ( $1 ) ( $2 )( $3 )( $4)
while regexp(string, expr)
% Iterating is necessary to catch all occurrences. See above.
string = regexprep(string, expr, '$1{$2}$3$1{$4}');
end
% \text{ } should be a math-mode space
string = regexprep(string, '\\text\{(\s+)}', '$1');
% '<<' probably means 'much smaller than', i.e. '\ll'
repl = switchMatOct('$1\\ll{}$2', '$1\ll{}$2');
string = regexprep(string, '([^<])<<([^<])', repl);
% '>>' probably means 'much greater than', i.e. '\gg'
repl = switchMatOct('$1\\gg{}$2', '$1\gg{}$2');
string = regexprep(string, '([^>])>>([^>])', repl);
% Single letters are most likely variables and thus should be in math mode
string = regexprep(string, '\\text\{([a-zA-Z])\}', '$1');
end
end
% ==============================================================================
function tex = fonts2tex(fonts)
% Returns a tex command for each fontname in the cell array fonts.
if ~iscell(fonts)
error('matlab2tikz:fonts2tex', ...
'Expecting a cell array as input.');
end
tex = cell(size(fonts));
for ii = 1:numel(fonts)
font = fonts{ii}{1};
% List of known fonts.
switch lower(font)
case 'courier'
tex{ii} = '\ttfamily{}';
case 'times'
tex{ii} = '\rmfamily{}';
case {'arial', 'helvetica'}
tex{ii} = '\sffamily{}';
otherwise
warning('matlab2tikz:fonts2tex', ...
'Unknown font ''%s''. Using tex default font.',font);
% Unknown font -> Switch to standard font.
tex{ii} = '\rm{}';
end
end
end
% ==============================================================================
function string = mergeAdjacentTexCmds(string, cmd)
% Merges adjacent tex commands like \text into one command
% If necessary, add a backslash
if cmd(1) ~= '\'
cmd = ['\' cmd];
end
% Link each bracket to the corresponding bracket
link = zeros(size(string));
pos = [regexp([' ' string], '([^\\]{)'), ...
regexp([' ' string], '([^\\]})')];
pos = sort(pos);
ii = 1;
while ii <= numel(pos)
if string(pos(ii)) == '}'
link(pos(ii-1)) = pos(ii);
link(pos(ii)) = pos(ii - 1);
pos([ii-1, ii]) = [];
ii = ii - 1;
else
ii = ii + 1;
end
end
% Find dispensable commands
pos = regexp(string, ['}\' cmd '{']);
delete = zeros(0,1);
len = numel(cmd);
for p = pos
l = link(p);
if l > len && isequal(string(l-len:l-1), cmd)
delete(end+1,1) = p;
end
end
% 3. Remove these commands (starting from the back
delete = repmat(delete, 1, len+2) + repmat(0:len+1,numel(delete), 1);
string(delete(:)) = [];
end
function dims = pos2dims(pos)
% Position quadruplet [left, bottom, width, height] to dimension structure
dims = struct('left' , pos(1), 'bottom', pos(2));
if numel(pos) == 4
dims.width = pos(3);
dims.height = pos(4);
dims.right = dims.left + dims.width;
dims.top = dims.bottom + dims.height;
end
end
% OPTION ARRAYS ================================================================
function opts = opts_new()
% create a new options array
opts = cell(0,2);
end
function opts = opts_add(opts, key, value)
% add a key-value pair to an options array (with duplication check)
if ~exist('value','var')
value = '';
end
value = char(value);
% Check if the key already exists.
if opts_has(opts, key)
oldValue = opts_get(opts, key);
if isequal(value, oldValue)
return; % no action needed: value already present
else
error('matlab2tikz:opts_add', ...
['Trying to add (%s, %s) to options, but it already ' ...
'contains the conflicting key-value pair (%s, %s).'], ...
key, value, key, oldValue);
end
end
opts = opts_append(opts, key, value);
end
function opts = opts_addSubOpts(opts, key, subOpts)
% add a key={Opts} pair to an options array
formatted = ['{' opts_print(subOpts) '}'];
opts = opts_add(opts, key, formatted);
end
function bool = opts_has(opts, key)
% returns true if the options array contains the key
bool = ~isempty(opts) && ismember(key, opts(:,1));
end
function value = opts_get(opts, key)
% returns the value(s) stored for a key in an options array
idx = find(ismember(opts(:,1), key));
switch numel(idx)
case 1
value = opts{idx,2}; % just the value
otherwise
value = opts(idx,2); % as cell array
end
end
function opts = opts_append(opts, key, value)
% append a key-value pair to an options array (duplicate keys allowed)
if ~exist('value','var')
value = '';
end
value = char(value);
if ~(opts_has(opts, key) && isequal(opts_get(opts, key), value))
opts = cat(1, opts, {key, value});
end
end
function opts = opts_append_userdefined(opts, userDefined)
% appends user-defined options to an options array
% the userDefined options can come either as a single string or a cellstr that
% is already TikZ-formatted. The internal 2D cell format is NOT supported.
if ~isempty(userDefined)
if ischar(userDefined)
userDefined = {userDefined};
end
for k = 1:length(userDefined)
opts = opts_append(opts, userDefined{k});
end
end
end
function opts = opts_copy(opts_from, name_from, opts, name_to)
% copies an option (if it exists) from one option array to another one
if ~exist('name_to', 'var') || isempty(name_to)
name_to = name_from;
end
if opts_has(opts_from, name_from)
value = opts_get(opts_from, name_from);
opts = opts_append(opts, name_to, value);
end
end
function opts = opts_remove(opts, varargin)
% remove some key-value pairs from an options array
keysToDelete = varargin;
idxToDelete = ismember(opts(:,1), keysToDelete);
opts(idxToDelete, :) = [];
end
function opts = opts_merge(opts, varargin)
% merge multiple options arrays
for jArg = 1:numel(varargin)
opts2 = varargin{jArg};
for k = 1:size(opts2, 1)
opts = opts_append(opts, opts2{k,1}, opts2{k,2});
end
end
end
function str = opts_print(opts, sep)
% pretty print an options array
if ~exist('sep','var') || ~ischar(sep)
sep = ', ';
end
nOpts = size(opts,1);
c = cell(1,nOpts);
for k = 1:nOpts
if isempty(opts{k,2})
c{k} = sprintf('%s', opts{k,1});
else
c{k} = sprintf('%s=%s', opts{k,1}, opts{k,2});
end
end
str = m2tstrjoin(c, sep);
end
% ==============================================================================
function m2t = m2t_addAxisOption(m2t, key, value)
% Adds an option to the last axesContainer
if ~exist('value','var')
value = '';
end
m2t.axes{end}.options = opts_add(m2t.axes{end}.options, key, value);
end
% ==============================================================================
function bool = isHG2()
% Checks if graphics system is HG2 (true) or HG1 (false).
% HG1 : MATLAB up to R2014a and currently all OCTAVE versions
% HG2 : MATLAB starting from R2014b (version 8.4)
[env, envVersion] = getEnvironment();
bool = strcmpi(env,'MATLAB') && ~isVersionBelow(envVersion, [8,4]);
end
% ==============================================================================
function str = formatAspectRatio(m2t, values)
% format the aspect ratio. Behind the scenes, formatDim is used
strs = arrayfun(@formatDim, values, 'UniformOutput', false);
str = join(m2t, strs, ' ');
end
% ==============================================================================
function str = formatDim(value, unit)
% format the value for use as a TeX dimension
if ~exist('unit','var') || isempty(unit)
unit = '';
end
tolerance = 1e-7;
value = round(value/tolerance)*tolerance;
if value == 1 && ~isempty(unit) && unit(1) == '\'
str = unit; % just use the unit
else
% LaTeX has support for single precision (about 6.5 decimal places),
% but such accuracy is overkill for positioning. We clip to three
% decimals to overcome numerical rounding issues that tend to be very
% platform and version dependent. See also #604.
str = sprintf('%.3f', value);
str = regexprep(str, '(\d*\.\d*?)0+$', '$1'); % remove trailing zeros
str = regexprep(str, '\.$', ''); % remove trailing period
str = [str unit];
end
end
% ==============================================================================
function [retval] = switchMatOct(matlabValue, octaveValue)
% Returns a different value for MATLAB and Octave
switch getEnvironment
case 'MATLAB'
retval = matlabValue;
case 'Octave'
retval = octaveValue;
otherwise
errorUnknownEnvironment();
end
end
% ==============================================================================
function checkDeprecatedEnvironment(minimalVersions)
[env, envVersion] = getEnvironment();
if isfield(minimalVersions, env)
minVersion = minimalVersions.(env);
envWithVersion = sprintf('%s %s', env, minVersion.name);
if isVersionBelow(envVersion, minVersion.num)
ID = 'matlab2tikz:deprecatedEnvironment';
warningMessage = ['\n', repmat('=',1,80), '\n\n', ...
' matlab2tikz is tested and developed on %s and newer.\n', ...
' This script may still be able to handle your plots, but if you\n', ...
' hit a bug, please consider upgrading your environment first.\n', ...
' Type "warning off %s" to suppress this warning.\n', ...
'\n', repmat('=',1,80), ];
warning(ID, warningMessage, envWithVersion, ID);
end
else
errorUnknownEnvironment();
end
end
% ==============================================================================
function m2t = needsPgfplotsVersion(m2t, minVersion)
if isVersionBelow(m2t.pgfplotsVersion, minVersion)
m2t.pgfplotsVersion = minVersion;
end
end
% ==============================================================================
function str = formatPgfplotsVersion(version)
version = versionArray(version);
if all(isfinite(version))
str = sprintf('%d.',version);
str = str(1:end-1); % remove the last period
else
str = 'newest';
end
end
% ==============================================================================
function [formatted,treeish] = VersionControlIdentifier()
% This function gives the (git) commit ID of matlab2tikz
%
% This assumes the standard directory structure as used by Nico's master branch:
% SOMEPATH/src/matlab2tikz.m with a .git directory in SOMEPATH.
%
% The HEAD of that repository is determined from file system information only
% by following dynamic references (e.g. ref:refs/heds/master) in branch files
% until an absolute commit hash (e.g. 1a3c9d1...) is found.
% NOTE: Packed branch references are NOT supported by this approach
MAXITER = 10; % stop following dynamic references after a while
formatted = '';
REFPREFIX = 'ref:';
isReference = @(treeish)(any(strfind(treeish, REFPREFIX)));
treeish = [REFPREFIX 'HEAD'];
try
% get the matlab2tikz directory
m2tDir = fileparts(mfilename('fullpath'));
gitDir = fullfile(m2tDir,'..','.git');
nIter = 1;
while isReference(treeish)
refName = treeish(numel(REFPREFIX)+1:end);
branchFile = fullfile(gitDir, refName);
if exist(branchFile, 'file') && nIter < MAXITER
% The FID is reused in every iteration, so `onCleanup` cannot
% be used to `fclose(fid)`. But since there is very little that
% can go wrong in a single `fscanf`, it's probably best to leave
% this part as it is for the time being.
fid = fopen(branchFile,'r');
treeish = fscanf(fid,'%s');
fclose(fid);
nIter = nIter + 1;
else % no branch file or iteration limit reached
treeish = '';
return;
end
end
catch
treeish = '';
end
if ~isempty(treeish)
formatted = sprintf('(commit %s)',treeish);
end
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
figure2dot.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/figure2dot.m
| 4,518 |
utf_8
|
facdd508e157dc90d825c51db03ead9a
|
function figure2dot(filename, varargin)
%FIGURE2DOT Save figure in Graphviz (.dot) file.
% FIGURE2DOT(filename) saves the current figure as dot-file.
%
% FIGURE2DOT(filename, 'object', HGOBJECT) constructs the graph representation
% of the specified object (default: gcf)
%
% You can visualize the constructed DOT file using:
% - [GraphViz](http://www.graphviz.org) on your computer
% - [WebGraphViz](http://www.webgraphviz.com) online
% - [Gravizo](http://www.gravizo.com) for your markdown files
% - and a lot of other software such as OmniGraffle
%
% See also: matlab2tikz, cleanfigure, uiinspect, inspect
ipp = m2tInputParser();
ipp = ipp.addRequired(ipp, 'filename', @ischar);
ipp = ipp.addParamValue(ipp, 'object', gcf, @ishghandle);
ipp = ipp.parse(ipp, filename, varargin{:});
args = ipp.Results;
filehandle = fopen(args.filename, 'w');
finally_fclose_filehandle = onCleanup(@() fclose(filehandle));
% start printing
fprintf(filehandle, 'digraph simple_hierarchy {\n\n');
fprintf(filehandle, 'node[shape=box];\n\n');
% define the root node
node_number = 0;
p = get(args.object, 'Parent');
% define root element
type = get(p, 'Type');
fprintf(filehandle, 'N%d [label="%s"]\n\n', node_number, type);
% start recursion
plot_children(filehandle, p, node_number);
% finish off
fprintf(filehandle, '}');
% ----------------------------------------------------------------------------
function plot_children(fh, h, parent_node)
children = allchild(h);
for h = children(:)'
if shouldSkip(h), continue, end;
node_number = node_number + 1;
label = {};
label = addHGProperty(label, h, 'Type', '');
try
hClass = class(handle(h));
label = addProperty(label, 'Class', hClass);
catch
% don't do anything
end
label = addProperty(label, 'Handle', sprintf('%g', double(h)));
label = addHGProperty(label, h, 'Title', '');
label = addHGProperty(label, h, 'Axes', []);
label = addHGProperty(label, h, 'String', '');
label = addHGProperty(label, h, 'Tag', '');
label = addHGProperty(label, h, 'DisplayName', '');
label = addHGProperty(label, h, 'Visible', 'on');
label = addHGProperty(label, h, 'HandleVisibility', 'on');
% print node
fprintf(fh, 'N%d [label="%s"]\n', ...
node_number, m2tstrjoin(label, '\n'));
% connect to the child
fprintf(fh, 'N%d -> N%d;\n\n', parent_node, node_number);
% recurse
plot_children(fh, h, node_number);
end
end
end
% ==============================================================================
function bool = shouldSkip(h)
% returns TRUE for objects that can be skipped
objType = get(h, 'Type');
bool = ismember(lower(objType), guitypes());
end
% ==============================================================================
function label = addHGProperty(label, h, propName, default)
% get a HG property and assign it to a GraphViz node label
if ~exist('default','var') || isempty(default)
shouldOmit = @isempty;
elseif isa(default, 'function_handle')
shouldOmit = default;
else
shouldOmit = @(v) isequal(v,default);
end
if isprop(h, propName)
propValue = get(h, propName);
if numel(propValue) == 1 && ishghandle(propValue) && isprop(propValue, 'String')
% dereference Titles, labels, ...
propValue = get(propValue, 'String');
elseif ishghandle(propValue)
% dereference other HG objects to their raw handle value (double)
propValue = double(propValue);
elseif iscell(propValue)
propValue = ['{' m2tstrjoin(propValue,',') '}'];
end
if ~shouldOmit(propValue)
label = addProperty(label, propName, propValue);
end
end
end
function label = addProperty(label, propName, propValue)
% add a property to a GraphViz node label
if isnumeric(propValue)
propValue = num2str(propValue);
elseif iscell(propValue)
propValue = m2tstrjoin(propValue,sprintf('\n'));
end
label = [label, sprintf('%s: %s', propName, propValue)];
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
m2tInputParser.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/m2tInputParser.m
| 7,838 |
utf_8
|
5df224f2df7d02ffce9af7a01a28b080
|
function parser = m2tInputParser()
%MATLAB2TIKZINPUTPARSER Input parsing for matlab2tikz.
% This implementation exists because Octave is lacking one.
% Initialize the structure.
parser = struct ();
% Public Properties
parser.Results = {};
% Enabel/disable parameters case sensitivity.
parser.CaseSensitive = false;
% Keep parameters not defined by the constructor.
parser.KeepUnmatched = false;
% Enable/disable warning for parameters not defined by the constructor.
parser.WarnUnmatched = true;
% Enable/disable passing arguments in a structure.
parser.StructExpand = true;
% Names of parameters defined in input parser constructor.
parser.Parameters = {};
% Names of parameters not defined in the constructor.
parser.Unmatched = struct ();
% Names of parameters using default values.
parser.UsingDefaults = {};
% Names of deprecated parameters and their alternatives
parser.DeprecatedParameters = struct();
% Handles for functions that act on the object.
parser.addRequired = @addRequired;
parser.addOptional = @addOptional;
parser.addParamValue = @addParamValue;
parser.deprecateParam = @deprecateParam;
parser.parse = @parse;
% Initialize the parser plan
parser.plan = {};
end
% =========================================================================
function p = parser_plan (q, arg_type, name, default, validator)
p = q;
plan = p.plan;
if (isempty (plan))
plan = struct ();
n = 1;
else
n = numel (plan) + 1;
end
plan(n).type = arg_type;
plan(n).name = name;
plan(n).default = default;
plan(n).validator = validator;
p.plan = plan;
end
% =========================================================================
function p = addRequired (p, name, validator)
p = parser_plan (p, 'required', name, [], validator);
end
% =========================================================================
function p = addOptional (p, name, default, validator)
p = parser_plan (p, 'optional', name, default, validator);
end
% =========================================================================
function p = addParamValue (p, name, default, validator)
p = parser_plan (p, 'paramvalue', name, default, validator);
end
% =========================================================================
function p = deprecateParam (p, name, alternatives)
if isempty(alternatives)
alternatives = {};
elseif ischar(alternatives)
alternatives = {alternatives}; % make cellstr
elseif ~iscellstr(alternatives)
error('m2tInputParser:BadAlternatives',...
'Alternatives for a deprecated parameter must be a char or cellstr');
end
p.DeprecatedParameters.(name) = alternatives;
end
% =========================================================================
function p = parse (p, varargin)
plan = p.plan;
results = p.Results;
using_defaults = {};
if (p.CaseSensitive)
name_cmp = @strcmp;
else
name_cmp = @strcmpi;
end
if (p.StructExpand)
k = find (cellfun (@isstruct, varargin));
for m = numel(k):-1:1
n = k(m);
s = varargin{n};
c = [fieldnames(s).'; struct2cell(s).'];
c = c(:).';
if (n > 1 && n < numel (varargin))
varargin = horzcat (varargin(1:n-1), c, varargin(n+1:end));
elseif (numel (varargin) == 1)
varargin = c;
elseif (n == 1);
varargin = horzcat (c, varargin(n+1:end));
else % n == numel (varargin)
varargin = horzcat (varargin(1:n-1), c);
end
end
end
if (isempty (results))
results = struct ();
end
type = {plan.type};
n = find( strcmp( type, 'paramvalue' ) );
m = setdiff (1:numel( plan ), n );
plan = plan ([n,m]);
for n = 1 : numel (plan)
found = false;
results.(plan(n).name) = plan(n).default;
if (~ isempty (varargin))
switch plan(n).type
case 'required'
found = true;
if (strcmpi (varargin{1}, plan(n).name))
varargin(1) = [];
end
value = varargin{1};
varargin(1) = [];
case 'optional'
m = find (cellfun (@ischar, varargin));
k = find (name_cmp (plan(n).name, varargin(m)));
if (isempty (k) && validate_arg (plan(n).validator, varargin{1}))
found = true;
value = varargin{1};
varargin(1) = [];
elseif (~ isempty (k))
m = m(k);
found = true;
value = varargin{max(m)+1};
varargin(union(m,m+1)) = [];
end
case 'paramvalue'
m = find( cellfun (@ischar, varargin) );
k = find (name_cmp (plan(n).name, varargin(m)));
if (~ isempty (k))
found = true;
m = m(k);
value = varargin{max(m)+1};
varargin(union(m,m+1)) = [];
end
otherwise
error( sprintf ('%s:parse', mfilename), ...
'parse (%s): Invalid argument type.', mfilename ...
)
end
end
if (found)
if (validate_arg (plan(n).validator, value))
results.(plan(n).name) = value;
else
error( sprintf ('%s:invalidinput', mfilename), ...
'%s: Input argument ''%s'' has invalid value.\n', mfilename, plan(n).name ...
);
end
p.Parameters = union (p.Parameters, {plan(n).name});
elseif (strcmp (plan(n).type, 'required'))
error( sprintf ('%s:missinginput', mfilename), ...
'%s: input ''%s'' is missing.\n', mfilename, plan(n).name ...
);
else
using_defaults = union (using_defaults, {plan(n).name});
end
end
if ~isempty(varargin)
% Include properties that do not match specified properties
for n = 1:2:numel(varargin)
if ischar(varargin{n})
if p.KeepUnmatched
results.(varargin{n}) = varargin{n+1};
end
if p.WarnUnmatched
warning(sprintf('%s:unmatchedArgument',mfilename), ...
'Ignoring unknown argument "%s"', varargin{n});
end
p.Unmatched.(varargin{n}) = varargin{n+1};
else
error (sprintf ('%s:invalidinput', mfilename), ...
'%s: invalid input', mfilename)
end
end
end
% Store the results of the parsing
p.Results = results;
p.UsingDefaults = using_defaults;
warnForDeprecatedParameters(p);
end
% =========================================================================
function result = validate_arg (validator, arg)
try
result = validator (arg);
catch %#ok
result = false;
end
end
% =========================================================================
function warnForDeprecatedParameters(p)
usedDeprecatedParameters = intersect(p.Parameters, fieldnames(p.DeprecatedParameters));
for iParam = 1:numel(usedDeprecatedParameters)
oldParameter = usedDeprecatedParameters{iParam};
alternatives = p.DeprecatedParameters.(oldParameter);
switch numel(alternatives)
case 0
replacements = '';
case 1
replacements = ['''' alternatives{1} ''''];
otherwise
replacements = deblank(sprintf('''%s'' and ',alternatives{:}));
replacements = regexprep(replacements,' and$','');
end
if ~isempty(replacements)
replacements = sprintf('From now on, please use %s to control the output.\n',replacements);
end
message = ['\n===============================================================================\n', ...
'You are using the deprecated parameter ''%s''.\n', ...
'%s', ...
'==============================================================================='];
warning('matlab2tikz:deprecatedParameter', ...
message, oldParameter, replacements);
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
cleanfigure.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/cleanfigure.m
| 47,146 |
utf_8
|
377c29df83de72042593b26251aeab91
|
function cleanfigure(varargin)
% CLEANFIGURE() removes the unnecessary objects from your MATLAB plot
% to give you a better experience with matlab2tikz.
% CLEANFIGURE comes with several options that can be combined at will.
%
% CLEANFIGURE('handle',HANDLE,...) explicitly specifies the
% handle of the figure that is to be stored. (default: gcf)
%
% CLEANFIGURE('pruneText',BOOL,...) explicitly specifies whether text
% should be pruned. (default: true)
%
% CLEANFIGURE('targetResolution',PPI,...)
% CLEANFIGURE('targetResolution',[W,H],...)
% Reduce the number of data points in line objects by applying
% unperceivable changes at the target resolution.
% The target resolution can be specificed as the number of Pixels Per
% Inch (PPI), e.g. 300, or as the Width and Heigth of the figure in
% pixels, e.g. [9000, 5400].
% Use targetResolution = Inf or 0 to disable line simplification.
% (default: 600)
%
% CLEANFIGURE('scalePrecision',alpha,...)
% Scale the precision the data is represented with. Setting it to 0
% or negative values disable this feature.
% (default: 1)
%
% CLEANFIGURE('normalizeAxis','xyz',...)
% EXPERIMENTAL: Normalize the data of the dimensions specified by
% 'normalizeAxis' to the interval [0, 1]. This might have side effects
% with hgtransform and friends. One can directly pass the axis handle to
% cleanfigure to ensure that only one axis gets normalized.
% Usage: Input 'xz' normalizes only x- and zData but not yData
% (default: '')
%
% Example
% x = -pi:pi/1000:pi;
% y = tan(sin(x)) - sin(tan(x));
% plot(x,y,'--rs');
% cleanfigure();
%
% See also: matlab2tikz
% Treat hidden handles, too.
shh = get(0, 'ShowHiddenHandles');
set(0, 'ShowHiddenHandles', 'on');
% Keep track of the current axes.
meta.gca = [];
% Set up command line options.
m2t.cmdOpts = m2tInputParser;
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'handle', gcf, @ishandle);
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'targetResolution', 600, @isValidTargetResolution);
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'pruneText', true, @islogical);
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'minimumPointsDistance', 1.0e-10, @isnumeric);
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'scalePrecision', 1, @isnumeric);
m2t.cmdOpts = m2t.cmdOpts.addParamValue(m2t.cmdOpts, 'normalizeAxis', '', @isValidAxis);
% Deprecated parameters
m2t.cmdOpts = m2t.cmdOpts.deprecateParam(m2t.cmdOpts, 'minimumPointsDistance', 'targetResolution');
% Finally parse all the elements.
m2t.cmdOpts = m2t.cmdOpts.parse(m2t.cmdOpts, varargin{:});
% Recurse down the tree of plot objects and clean up the leaves.
for h = m2t.cmdOpts.Results.handle(:)'
recursiveCleanup(meta, h, m2t.cmdOpts.Results);
end
% Reset to initial state.
set(0, 'ShowHiddenHandles', shh);
return;
end
% =========================================================================
function recursiveCleanup(meta, h, cmdOpts)
% Recursive function, that cleans up the individual childs of a figure
% Get the type of the current figure handle
type = get(h, 'Type');
%display(sprintf([repmat(' ',1,indent), type, '->']))
% Don't try to be smart about quiver groups.
% NOTE:
% A better way to write `strcmp(get(h,...))` would be to use
% isa(handle(h), 'specgraph.quivergroup').
% The handle() function isn't supported by Octave, though, so let's stick
% with strcmp().
if strcmp(type, 'specgraph.quivergroup')
%if strcmp(class(handle(h)), 'specgraph.quivergroup')
return;
end
% Update the current axes.
if strcmp(type, 'axes')
meta.gca = h;
if ~isempty(cmdOpts.normalizeAxis)
% If chosen transform the date axis
normalizeAxis(h, cmdOpts);
end
end
children = get(h, 'Children');
if ~isempty(children)
for child = children(:)'
recursiveCleanup(meta, child, cmdOpts);
end
else
if strcmp(type, 'line')
% Remove data points outside of the axes
% NOTE: Always remove invisible points before simplifying the
% line. Otherwise it will generate additional line segments
pruneOutsideBox(meta, h);
% Move some points closer to the box to avoid TeX:DimensionTooLarge
% errors. This may involve inserting extra points.
movePointsCloser(meta, h);
% Simplify the lines by removing superflous points
simplifyLine(meta, h, cmdOpts.targetResolution);
% Limit the precision of the output
limitPrecision(meta, h, cmdOpts.scalePrecision);
elseif strcmpi(type, 'stair')
% Remove data points outside of the visible axes
pruneOutsideBox(meta, h);
% Remove superfluous data points
simplifyStairs(meta, h);
% Limit the precision of the output
limitPrecision(meta, h, cmdOpts.scalePrecision);
elseif strcmp(type, 'text') && cmdOpts.pruneText
% Prune text that is outside of the axes
pruneOutsideText(meta, h);
end
end
return;
end
% =========================================================================
function pruneOutsideBox(meta, handle)
% Some sections of the line may sit outside of the visible box.
% Cut those off.
% Extract the visual data from the current line handle.
[xData, yData] = getVisualData(meta, handle);
% Merge the data into one matrix
data = [xData, yData];
% Dont do anything if the data is empty
if isempty(data)
return;
end
% Check if the plot has lines
hasLines = ~strcmp(get(handle, 'LineStyle'),'none')...
&& get(handle, 'LineWidth') > 0.0;
% Extract the visual limits from the current line handle.
[xLim, yLim]= getVisualLimits(meta);
tol = 1.0e-10;
relaxedXLim = xLim + [-tol, tol];
relaxedYLim = yLim + [-tol, tol];
% Get which points are inside a (slightly larger) box.
dataIsInBox = isInBox(data, relaxedXLim, relaxedYLim);
% Plot all the points inside the box
shouldPlot = dataIsInBox;
if hasLines
% Check if the connecting line between two data points is visible.
segvis = segmentVisible(data, dataIsInBox, xLim, yLim);
% Plot points which part of an visible line segment.
shouldPlot = shouldPlot | [false; segvis] | [segvis; false];
end
% Remove or replace points outside the box
id_replace = [];
id_remove = [];
if ~all(shouldPlot)
% For line plots, simply removing the data has the disadvantage
% that the line between two 'loose' ends may now appear in the figure.
% To avoid this, add a row of NaNs wherever a block of actual data is
% removed.
% Get the indices of points that should be removed
id_remove = find(~shouldPlot);
% If there are consecutive data points to be removed, only replace
% the first one by a NaN. Consecutive data points have
% diff(id_remove)==1, so replace diff(id_remove)>1 by NaN and remove
% the rest
idx = [true; diff(id_remove) >1];
id_replace = id_remove(idx);
id_remove = id_remove(~idx);
end
% Replace the data points
replaceDataWithNaN(meta, handle, id_replace);
% Remove the data outside the box
removeData(meta, handle, id_remove);
% Remove possible NaN duplications
removeNaNs(meta, handle);
return;
end
% =========================================================================
function movePointsCloser(meta, handle)
% Move all points outside a box much larger than the visible one
% to the boundary of that box and make sure that lines in the visible
% box are preserved. This typically involves replacing one point by
% two new ones and a NaN.
% TODO: 3D simplification of frontal 2D projection. This requires the
% full transformation rather than the projection, as we have to calculate
% the inverse transformation to project back into 3D
if isAxis3D(meta.gca)
return;
end
% Extract the visual data from the current line handle.
[xData, yData] = getVisualData(meta, handle);
% Extract the visual limits from the current line handle.
[xLim, yLim] = getVisualLimits(meta);
% Calculate the extension of the extended box
xWidth = xLim(2) - xLim(1);
yWidth = yLim(2) - yLim(1);
% Don't choose the larger box too large to make sure that the values inside
% it can still be treated by TeX.
extendFactor = 0.1;
largeXLim = xLim + extendFactor * [-xWidth, xWidth];
largeYLim = yLim + extendFactor * [-yWidth, yWidth];
% Put the data into one matrix
data = [xData, yData];
% Get which points are in an extended box (the limits of which
% don't exceed TeX's memory).
dataIsInLargeBox = isInBox(data, largeXLim, largeYLim);
% Count the NaNs as being inside the box.
dataIsInLargeBox = dataIsInLargeBox | any(isnan(data), 2);
% Find all points which are to be included in the plot yet do not fit
% into the extended box
id_replace = find(~dataIsInLargeBox);
% Only try to replace points if there are some to replace
dataInsert = {};
if ~isempty(id_replace)
% Get the indices of those points, that are the first point in a
% segment. The last data point at size(data, 1) cannot be the first
% point in a segment.
id_first = id_replace(id_replace < size(data, 1));
% Get the indices of those points, that are the second point in a
% segment. Similarly the first data point cannot be the second data
% point in a segment.
id_second = id_replace(id_replace > 1);
% Define the vectors of data points for the segments X1--X2
X1_first = data(id_first, :);
X2_first = data(id_first+1, :);
X1_second = data(id_second, :);
X2_second = data(id_second-1, :);
% Move the points closer to the large box along the segment
newData_first = moveToBox(X1_first, X2_first, largeXLim, largeYLim);
newData_second= moveToBox(X1_second, X2_second, largeXLim, largeYLim);
% Respect logarithmic scaling for the new points
isXlog = strcmp(get(meta.gca, 'XScale'), 'log');
if isXlog
newData_first (:, 1) = 10.^newData_first (:, 1);
newData_second(:, 1) = 10.^newData_second(:, 1);
end
isYlog = strcmp(get(meta.gca, 'YScale'), 'log');
if isYlog
newData_first (:, 2) = 10.^newData_first (:, 2);
newData_second(:, 2) = 10.^newData_second(:, 2);
end
% If newData_* is infinite, the segment was not visible. However, as we
% move the point closer, it would become visible. So insert a NaN.
isInfinite_first = any(~isfinite(newData_first), 2);
isInfinite_second = any(~isfinite(newData_second), 2);
newData_first (isInfinite_first, :) = NaN(sum(isInfinite_first), 2);
newData_second(isInfinite_second, :) = NaN(sum(isInfinite_second), 2);
% If a point is part of two segments, that cross the border, we need to
% insert a NaN to prevent an additional line segment
[trash, trash, id_conflict] = intersect(id_first (~isInfinite_first), ...
id_second(~isInfinite_second));
% Cut the data into length(id_replace)+1 segments.
% Calculate the length of the segments
length_segments = [id_replace(1);
diff(id_replace);
size(data, 1)-id_replace(end)];
% Create an empty cell array for inserting NaNs and fill it at the
% conflict sites
dataInsert_NaN = cell(length(length_segments),1);
dataInsert_NaN(id_conflict) = mat2cell(NaN(length(id_conflict), 2),...
ones(size(id_conflict)), 2);
% Create a cell array for the moved points
dataInsert_first = mat2cell(newData_first, ones(size(id_first)), 2);
dataInsert_second = mat2cell(newData_second, ones(size(id_second)), 2);
% Add an empty cell at the end of the last segment, as we do not
% insert something *after* the data
dataInsert_first = [dataInsert_first; cell(1)];
dataInsert_second = [dataInsert_second; cell(1)];
% If the first or the last point would have been replaced add an empty
% cell at the beginning/end. This is because the last data point
% cannot be the first data point of a line segment and vice versa.
if(id_replace(end) == size(data, 1))
dataInsert_first = [dataInsert_first; cell(1)];
end
if(id_replace(1) == 1)
dataInsert_second = [cell(1); dataInsert_second];
end
% Put the cells together, right points first, then the possible NaN
% and then the left points
dataInsert = cellfun(@(a,b,c) [a; b; c],...
dataInsert_second,...
dataInsert_NaN,...
dataInsert_first,...
'UniformOutput',false);
end
% Insert the data
insertData(meta, handle, id_replace, dataInsert);
% Get the indices of the to be removed points accounting for the now inserted
% data points
numPointsInserted = cellfun(@(x) size(x,1), [cell(1);dataInsert(1:end-2)]);
id_remove = id_replace + cumsum(numPointsInserted);
% Remove the data point that should be replaced.
removeData(meta, handle, id_remove);
% Remove possible NaN duplications
removeNaNs(meta, handle);
end
% =========================================================================
function simplifyLine(meta, handle, targetResolution)
% Reduce the number of data points in the line 'handle'.
%
% Aplies a path-simplification algorithm if there are no markers or
% pixelization otherwise. Changes are visually negligible at the target
% resolution.
%
% The target resolution is either specificed as the number of PPI or as
% the [Width, Heigth] of the figure in pixels.
% A scalar value of INF or 0 disables path simplification.
% (default = 600)
% Do not simpify
if any(isinf(targetResolution) | targetResolution == 0)
return
end
% Retrieve target figure size in pixels
[W, H] = getWidthHeightInPixels(targetResolution);
% Extract the visual data from the current line handle.
[xData, yData] = getVisualData(meta, handle);
% Only simplify if there are more than 2 points
if numel(xData) <= 2 || numel(yData) <= 2
return;
end
% Extract the visual limits from the current line handle.
[xLim, yLim] = getVisualLimits(meta);
% Automatically guess a tol based on the area of the figure and
% the area and resolution of the output
xRange = xLim(2)-xLim(1);
yRange = yLim(2)-yLim(1);
% Conversion factors of data units into pixels
xToPix = W/xRange;
yToPix = H/yRange;
% Mask for removing data points
id_remove = [];
% If the path has markers, perform pixelation instead of simplification
hasMarkers = ~strcmpi(get(handle,'Marker'),'none');
hasLines = ~strcmpi(get(handle,'LineStyle'),'none');
if hasMarkers && ~hasLines
% Pixelate data at the zoom multiplier
mask = pixelate(xData, yData, xToPix, yToPix);
id_remove = find(mask==0);
elseif hasLines && ~hasMarkers
% Get the width of a pixel
xPixelWidth = 1/xToPix;
yPixelWidth = 1/yToPix;
tol = min(xPixelWidth,yPixelWidth);
% Split up lines which are seperated by NaNs
id_nan = isnan(xData) | isnan(yData);
% If lines were separated by a NaN, diff(~id_nan) would give 1 for
% the start of a line and -1 for the index after the end of
% a line.
id_diff = diff([false; ~id_nan; false]);
lineStart = find(id_diff == 1);
lineEnd = find(id_diff == -1)-1;
numLines = numel(lineStart);
id_remove = cell(numLines, 1);
% Simplify the line segments
for ii = 1:numLines
% Actual data that inherits the simplifications
x = xData(lineStart(ii):lineEnd(ii));
y = yData(lineStart(ii):lineEnd(ii));
% Line simplification
if numel(x) > 2
mask = opheimSimplify(x, y, tol);
% Remove all those with mask==0 respecting the number of
% data points in the previous segments
id_remove{ii} = find(mask==0) + lineStart(ii) - 1;
end
end
% Merge the indices of the line segments
id_remove = cat(1, id_remove{:});
end
% Remove the data points
removeData(meta, handle, id_remove);
end
% =========================================================================
function simplifyStairs(meta, handle)
% This function simplifies stair plots by removeing superflous data
% points
% Some data might not lead to a new step in the stair. This is the case
% if the difference in one dimension is zero, e.g
% [(x_1, y_1), (x_2, y_1), ... (x_k, y_1), (x_{k+1} y_2)].
% However, there is one exeption. If the monotonicity of the other
% dimension changes, e.g. the sequence [0, 1], [0, -1], [0, 2]. This
% sequence cannot be simplified. Therefore, we check for monoticity too.
% As an example, we can remove the data points marked with x in the
% following stair
% o--x--o
% | |
% x o --x--o
% |
% o--x--o
% |
% o
% Extract the data
xData = get(handle, 'XData');
yData = get(handle, 'YData');
% Do not do anything if the data is empty
if isempty(xData) || isempty(yData)
return;
end
% Check for nonchanging data points
xNoDiff = [false, (diff(xData) == 0)];
yNoDiff = [false, (diff(yData) == 0)];
% Never remove the last data point
xNoDiff(end) = false;
yNoDiff(end) = false;
% Check for monotonicity (it changes if diff(sign)~=0)
xIsMonotone = [true, diff(sign(diff(xData)))==0, true];
yIsMonotone = [true, diff(sign(diff(yData)))==0, true];
% Only remove points when there is no difference in one dimension and no
% change in monotonicity in the other
xRemove = xNoDiff & yIsMonotone;
yRemove = yNoDiff & xIsMonotone;
% Plot only points, that generate a new step
id_remove = find(xRemove | yRemove);
% Remove the superfluous data
removeData(meta, handle, id_remove);
end
% =========================================================================
function limitPrecision(meta, handle, alpha)
% Limit the precision of the given data
% If alpha is 0 or negative do nothing
if alpha<=0
return
end
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if isAxis3D(meta.gca)
zData = get(handle, 'ZData');
end
% Check for log scaling
isXlog = strcmp(get(meta.gca, 'XScale'), 'log');
isYlog = strcmp(get(meta.gca, 'YScale'), 'log');
isZlog = strcmp(get(meta.gca, 'ZScale'), 'log');
% Put the data into a matrix and log bits into vector
if isAxis3D(meta.gca)
data = [xData(:), yData(:), zData(:)];
isLog = [isXlog, isYlog, isZlog];
else
data = [xData(:), yData(:)];
isLog = [isXlog, isYlog];
end
% Only do something if the data is not empty
if isempty(data) || all(isinf(data(:)))
return
end
% Scale to visual coordinates
data(:, isLog) = log10(data(:, isLog));
% Get the maximal value of the data, only considering finite values
maxValue = max(abs(data(isfinite(data))));
% The least significant bit is proportional to the numerical precision
% of the largest number. Scale it with a user defined value alpha
leastSignificantBit = eps(maxValue) * alpha;
% Round to precision and scale back
data = round(data / leastSignificantBit) * leastSignificantBit;
% Scale back in case of log scaling
data(:, isLog) = 10.^data(:, isLog);
% Set the new data.
set(handle, 'XData', data(:, 1));
set(handle, 'YData', data(:, 2));
if isAxis3D(meta.gca)
set(handle, 'zData', data(:, 3));
end
end
% =========================================================================
function pruneOutsideText(meta, handle)
% Function to prune text outside of axis handles.
% Ensure units of type 'data' (default) and restore the setting later
units_original = get(handle, 'Units');
set(handle, 'Units', 'data');
% Check if text is inside bounds by checking if the position is inside
% the x, y and z limits. This works for both 2D and 3D plots.
xLim = get(meta.gca, 'XLim');
yLim = get(meta.gca, 'YLim');
zLim = get(meta.gca, 'ZLim');
axLim = [xLim; yLim; zLim];
pos = get(handle, 'Position');
% If the axis is 2D, ignore the z component and consider the extend of
% the textbox
if ~isAxis3D(meta.gca)
pos(3) = 0;
% In 2D plots the 'extent' of the textbox is available and also
% considered to keep the textbox, if it is partially inside the axis
% limits.
extent = get(handle, 'Extent');
% Extend the actual axis limits by the extent of the textbox so that
% the textbox is not discarded, if it overlaps the axis.
axLim(1, 1) = axLim(1, 1) - extent(3); % x-limit is extended by width
axLim(2, 1) = axLim(2, 1) - extent(4); % y-limit is extended by height
end
% Check if the (extended) textbox is inside the axis limits
bPosInsideLim = ( pos' >= axLim(:,1) ) & ( pos' <= axLim(:,2) );
% Restore original units (after reading all dimensions)
set(handle, 'Units', units_original);
% Check if it is the title
isTitle = (handle == get(meta.gca, 'title'));
% Disable visibility if it is outside the limits and it is not
% the title
if ~all(bPosInsideLim) && ~isTitle
% Warn about to be deprecated text removal
warning('cleanfigure:textRemoval', ...
'Text removal by cleanfigure is planned to be deprecated');
% Artificially disable visibility. m2t will check and skip.
set(handle, 'Visible', 'off');
end
end
% =========================================================================
function mask = isInBox(data, xLim, yLim)
% Returns a mask that indicates, whether a data point is within the
% limits
mask = data(:, 1) > xLim(1) & data(:, 1) < xLim(2) ...
& data(:, 2) > yLim(1) & data(:, 2) < yLim(2);
end
% =========================================================================
function mask = segmentVisible(data, dataIsInBox, xLim, yLim)
% Given a bounding box {x,y}Lim, determine whether the line between all
% pairs of subsequent data points [data(idx,:)<-->data(idx+1,:)] is
% visible. There are two possible cases:
% 1: One of the data points is within the limits
% 2: The line segments between the datapoints crosses the bounding box
n = size(data, 1);
mask = false(n-1, 1);
% Only check if there is more than 1 point
if n>1
% Define the vectors of data points for the segments X1--X2
idx= 1:n-1;
X1 = data(idx, :);
X2 = data(idx+1, :);
% One of the neighbors is inside the box and the other is finite
thisVisible = (dataIsInBox(idx) & all(isfinite(X2), 2));
nextVisible = (dataIsInBox(idx+1) & all(isfinite(X1), 2));
% Get the corner coordinates
[bottomLeft, topLeft, bottomRight, topRight] = corners2D(xLim, yLim);
% Check if data points intersect with the borders of the plot
left = segmentsIntersect(X1, X2, bottomLeft , topLeft);
right = segmentsIntersect(X1, X2, bottomRight, topRight);
bottom = segmentsIntersect(X1, X2, bottomLeft , bottomRight);
top = segmentsIntersect(X1, X2, topLeft , topRight);
% Check the result
mask = thisVisible | nextVisible | left | right | top | bottom;
end
end
% =========================================================================
function mask = segmentsIntersect(X1, X2, X3, X4)
% Checks whether the segments X1--X2 and X3--X4 intersect.
lambda = crossLines(X1, X2, X3, X4);
% Check whether lambda is in bound
mask = 0.0 < lambda(:, 1) & lambda(:, 1) < 1.0 &...
0.0 < lambda(:, 2) & lambda(:, 2) < 1.0;
end
% =========================================================================
function mask = pixelate(x, y, xToPix, yToPix)
% Rough reduction of data points at a multiple of the target resolution
% The resolution is lost only beyond the multiplier magnification
mult = 2;
% Convert data to pixel units and magnify
dataPixel = round([x * xToPix * mult, ...
y * yToPix * mult]);
% Sort the pixels
[dataPixelSorted, id_orig] = sortrows(dataPixel);
% Find the duplicate pixels
mask_sorted = [true; diff(dataPixelSorted(:,1))~=0 | ...
diff(dataPixelSorted(:,2))~=0];
% Unwind the sorting
mask = false(size(x));
mask(id_orig) = mask_sorted;
% Set the first, last, as well as unique pixels to true
mask(1) = true;
mask(end) = true;
% Set NaNs to true
inan = isnan(x) | isnan(y);
mask(inan) = true;
end
% =========================================================================
function mask = opheimSimplify(x,y,tol)
% Opheim path simplification algorithm
%
% Given a path of vertices V and a tolerance TOL, the algorithm:
% 1. selects the first vertex as the KEY;
% 2. finds the first vertex farther than TOL from the KEY and links
% the two vertices with a LINE;
% 3. finds the last vertex from KEY which stays within TOL from the
% LINE and sets it to be the LAST vertex. Removes all points in
% between the KEY and the LAST vertex;
% 4. sets the KEY to the LAST vertex and restarts from step 2.
%
% The Opheim algorithm can produce unexpected results if the path
% returns back on itself while remaining within TOL from the LINE.
% This behaviour can be seen in the following example:
%
% x = [1,2,2,2,3];
% y = [1,1,2,1,1];
% tol < 1
%
% The algorithm undesirably removes the second last point. See
% https://github.com/matlab2tikz/matlab2tikz/pull/585#issuecomment-89397577
% for additional details.
%
% To rectify this issues, step 3 is modified to find the LAST vertex as
% follows:
% 3*. finds the last vertex from KEY which stays within TOL from the
% LINE, or the vertex that connected to its previous point forms
% a segment which spans an angle with LINE larger than 90
% degrees.
mask = false(size(x));
mask(1) = true;
mask(end) = true;
N = numel(x);
i = 1;
while i <= N-2
% Find first vertex farther than TOL from the KEY
j = i+1;
v = [x(j)-x(i); y(j)-y(i)];
while j < N && norm(v) <= tol
j = j+1;
v = [x(j)-x(i); y(j)-y(i)];
end
v = v/norm(v);
% Unit normal to the line between point i and point j
normal = [v(2);-v(1)];
% Find the last point which stays within TOL from the line
% connecting i to j, or the last point within a direction change
% of pi/2.
% Starts from the j+1 points, since all previous points are within
% TOL by construction.
while j < N
% Calculate the perpendicular distance from the i->j line
v1 = [x(j+1)-x(i); y(j+1)-y(i)];
d = abs(normal.'*v1);
if d > tol
break
end
% Calculate the angle between the line from the i->j and the
% line from j -> j+1. If
v2 = [x(j+1)-x(j); y(j+1)-y(j)];
anglecosine = v.'*v2;
if anglecosine <= 0;
break
end
j = j + 1;
end
i = j;
mask(i) = true;
end
end
% =========================================================================
function lambda = crossLines(X1, X2, X3, X4)
% Checks whether the segments X1--X2 and X3--X4 intersect.
% See https://en.wikipedia.org/wiki/Line-line_intersection for reference.
% Given four points X_k=(x_k,y_k), k\in{1,2,3,4}, and the two lines
% defined by those,
%
% L1(lambda) = X1 + lambda (X2 - X1)
% L2(lambda) = X3 + lambda (X4 - X3)
%
% returns the lambda for which they intersect (and Inf if they are parallel).
% Technically, one needs to solve the 2x2 equation system
%
% x1 + lambda1 (x2-x1) = x3 + lambda2 (x4-x3)
% y1 + lambda1 (y2-y1) = y3 + lambda2 (y4-y3)
%
% for lambda1 and lambda2.
% Now X1 is a vector of all data points X1 and X2 is a vector of all
% consecutive data points X2
% n is the number of segments (not points in the plot!)
n = size(X2, 1);
lambda = zeros(n, 2);
% Calculate the determinant of A = [X2-X1, -(X4-X3)];
% detA = -(X2(1)-X1(1))*(X4(2)-X3(2)) + (X2(2)-X1(2))*(X4(1)-X3(1))
% NOTE: Vectorized this is equivalent to the matrix multiplication
% [nx2] * [2x2] * [2x1] = [nx1]
detA = -(X2(:, 1)-X1(:, 1)) .* (X4(2)-X3(2)) + (X2(:, 2)-X1(:, 2)) .* (X4(1)-X3(1));
% Get the indices for nonzero elements
id_detA = detA~=0;
if any(id_detA)
% rhs = X3(:) - X1(:)
% NOTE: Originaly this was a [2x1] vector. However as we vectorize the
% calculation it is beneficial to treat it as an [nx2] matrix rather than a [2xn]
rhs = bsxfun(@minus, X3, X1);
% Calculate the inverse of A and lambda
% invA=[-(X4(2)-X3(2)), X4(1)-X3(1);...
% -(X2(2)-X1(2)), X2(1)-X1(1)] / detA
% lambda = invA * rhs
% Rotational matrix with sign flip. It transforms a given vector [a,b] by
% Rotate * [a,b] = [-b,a] as required for calculation of invA
Rotate = [0, -1; 1, 0];
% Rather than calculating invA first and then multiply with rhs to obtain
% lambda, directly calculate the respective terms
% The upper half of the 2x2 matrix is always the same and is given by:
% [-(X4(2)-X3(2)), X4(1)-X3(1)] / detA * rhs
% This is a matrix multiplication of the form [1x2] * [2x1] = [1x1]
% As we have transposed rhs we can write this as:
% rhs * Rotate * (X4-X3) => [nx2] * [2x2] * [2x1] = [nx1]
lambda(id_detA, 1) = (rhs(id_detA, :) * Rotate * (X4-X3)')./detA(id_detA);
% The lower half is dependent on (X2-X1) which is a matrix of size [nx2]
% [-(X2(2)-X1(2)), X2(1)-X1(1)] / detA * rhs
% As both (X2-X1) and rhs are matrices of size [nx2] there is no simple
% matrix multiplication leading to a [nx1] vector. Therefore, use the
% elementwise multiplication and sum over it
% sum( [nx2] * [2x2] .* [nx2], 2) = sum([nx2],2) = [nx1]
lambda(id_detA, 2) = sum(-(X2(id_detA, :)-X1(id_detA, :)) * Rotate .* rhs(id_detA, :), 2)./detA(id_detA);
end
end
% =========================================================================
function minAlpha = updateAlpha(X1, X2, X3, X4, minAlpha)
% Checks whether the segments X1--X2 and X3--X4 intersect.
lambda = crossLines(X1, X2, X3, X4);
% Check if lambda is in bounds and lambda1 large enough
id_Alpha = 0.0 < lambda(:,2) & lambda(:,2) < 1.0 ...
& abs(minAlpha) > abs(lambda(:,1));
% Update alpha when applicable
minAlpha(id_Alpha) = lambda(id_Alpha,1);
end
% =========================================================================
function xNew = moveToBox(x, xRef, xLim, yLim)
% Takes a box defined by xlim, ylim, a vector of points x and a vector of
% reference points xRef.
% Returns the vector of points xNew that sits on the line segment between
% x and xRef *and* on the box. If several such points exist, take the
% closest one to x.
n = size(x, 1);
% Find out with which border the line x---xRef intersects, and determine
% the smallest parameter alpha such that x + alpha*(xRef-x)
% sits on the boundary. Otherwise set Alpha to inf.
minAlpha = inf(n, 1);
% Get the corner points
[bottomLeft, topLeft, bottomRight, topRight] = corners2D(xLim, yLim);
% left boundary:
minAlpha = updateAlpha(x, xRef, bottomLeft, topLeft, minAlpha);
% bottom boundary:
minAlpha = updateAlpha(x, xRef, bottomLeft, bottomRight, minAlpha);
% right boundary:
minAlpha = updateAlpha(x, xRef, bottomRight, topRight, minAlpha);
% top boundary:
minAlpha = updateAlpha(x, xRef, topLeft, topRight, minAlpha);
% Create the new point
xNew = x + bsxfun(@times ,minAlpha, (xRef-x));
end
% =========================================================================
function [xData, yData] = getVisualData(meta, handle)
% Returns the visual representation of the data (Respecting possible
% log_scaling and projection into the image plane)
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if is3D
zData = get(handle, 'ZData');
end
% Get info about log scaling
isXlog = strcmp(get(meta.gca, 'XScale'), 'log');
if isXlog
xData = log10(xData);
end
isYlog = strcmp(get(meta.gca, 'YScale'), 'log');
if isYlog
yData = log10(yData);
end
isZlog = strcmp(get(meta.gca, 'ZScale'), 'log');
if isZlog
zData = log10(zData);
end
% In case of 3D plots, project the data into the image plane.
if is3D
% Get the projection matrix
P = getProjectionMatrix(meta);
% Put the data into one matrix accounting for the canonical 4th
% dimension
data = [xData(:), yData(:), zData(:), ones(size(xData(:)))];
% Project the data into the image plane
dataProjected = P * data';
% Only consider the x and y coordinates and scale them correctly
xData = dataProjected(1, :) ./ dataProjected(4, :);
yData = dataProjected(2, :) ./ dataProjected(4, :);
end
% Turn the data into a row vector
xData = xData(:);
yData = yData(:);
end
% =========================================================================
function [xLim, yLim] = getVisualLimits(meta)
% Returns the visual representation of the axis limits (Respecting
% possible log_scaling and projection into the image plane)
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Get the axis limits
xLim = get(meta.gca, 'XLim');
yLim = get(meta.gca, 'YLim');
zLim = get(meta.gca, 'ZLim');
% Check for logarithmic scales
isXlog = strcmp(get(meta.gca, 'XScale'), 'log');
if isXlog
xLim = log10(xLim);
end
isYlog = strcmp(get(meta.gca, 'YScale'), 'log');
if isYlog
yLim = log10(yLim);
end
isZlog = strcmp(get(meta.gca, 'ZScale'), 'log');
if isZlog
zLim = log10(zLim);
end
% In case of 3D plots, project the limits into the image plane. Depending
% on the angles, any of the 8 corners of the 3D cube mit be relevant so
% check for all
if is3D
% Get the projection matrix
P = getProjectionMatrix(meta);
% Get the coordinates of the 8 corners
corners = corners3D(xLim, yLim, zLim);
% Add the canonical 4th dimension
corners = [corners, ones(8,1)];
% Project the corner points to 2D coordinates
cornersProjected = P * corners';
% Pick the x and y values of the projected corners and scale them
% correctly
xCorners = cornersProjected(1, :) ./ cornersProjected(4, :);
yCorners = cornersProjected(2, :) ./ cornersProjected(4, :);
% Get the maximal and minimal values of the x and y coordinates as
% limits
xLim = [min(xCorners), max(xCorners)];
yLim = [min(yCorners), max(yCorners)];
end
end
% =========================================================================
function replaceDataWithNaN(meta, handle, id_replace)
% Replaces data at id_replace with NaNs
% Only do something if id_replace is not empty
if isempty(id_replace)
return
end
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if is3D
zData = get(handle, 'ZData');
end
% Update the data indicated by id_update
xData(id_replace) = NaN(size(id_replace));
yData(id_replace) = NaN(size(id_replace));
if is3D
zData(id_replace) = NaN(size(id_replace));
end
% Set the new (masked) data.
set(handle, 'XData', xData);
set(handle, 'YData', yData);
if is3D
set(handle, 'ZData', zData);
end
end
% =========================================================================
function insertData(meta, handle, id_insert, dataInsert)
% Inserts the elements of the cell array dataInsert at position id_insert
% Only do something if id_insert is not empty
if isempty(id_insert)
return
end
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if is3D
zData = get(handle, 'ZData');
end
length_segments = [id_insert(1);
diff(id_insert);
length(xData)-id_insert(end)];
% Put the data into one matrix
if is3D
data = [xData(:), yData(:), zData(:)];
else
data = [xData(:), yData(:)];
end
% Cut the data into segments
dataCell = mat2cell(data, length_segments, size(data, 2));
% Merge the cell arrays
dataCell = [dataCell';
dataInsert'];
% Merge the cells back together
data = cat(1, dataCell{:});
% Set the new (masked) data.
set(handle, 'XData', data(:, 1));
set(handle, 'YData', data(:, 2));
if is3D
set(handle, 'ZData', data(:, 3));
end
end
% =========================================================================
function removeData(meta, handle, id_remove)
% Removes the data at position id_remove
% Only do something if id_remove is not empty
if isempty(id_remove)
return
end
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if is3D
zData = get(handle, 'ZData');
end
% Remove the data indicated by id_remove
xData(id_remove) = [];
yData(id_remove) = [];
if is3D
zData(id_remove) = [];
end
% Set the new data.
set(handle, 'XData', xData);
set(handle, 'YData', yData);
if is3D
set(handle, 'ZData', zData);
end
end
% =========================================================================
function removeNaNs(meta, handle)
% Removes superflous NaNs in the data, i.e. those at the end/beginning of
% the data and consequtive ones.
% Check whether this is a 3D plot
is3D = isAxis3D(meta.gca);
% Extract the data from the current line handle.
xData = get(handle, 'XData');
yData = get(handle, 'YData');
if is3D
zData = get(handle, 'ZData');
end
% Put the data into one matrix
if is3D
data = [xData(:), yData(:), zData(:)];
else
data = [xData(:), yData(:)];
end
% Remove consecutive NaNs
id_nan = any(isnan(data), 2);
id_remove = find(id_nan);
% If a NaN is preceeded by another NaN, then diff(id_remove)==1
id_remove = id_remove(diff(id_remove) == 1);
% Make sure that there are no NaNs at the beginning of the data since
% this would be interpreted as column names by Pgfplots.
% Also drop all NaNs at the end of the data
id_first = find(~id_nan, 1, 'first');
id_last = find(~id_nan, 1, 'last');
% If there are only NaN data points, remove the whole data
if isempty(id_first)
id_remove = 1:length(xData);
else
id_remove = [1:id_first-1, id_remove', id_last+1:length(xData)]';
end
% Remove the NaNs
data(id_remove,:) = [];
% Set the new data.
set(handle, 'XData', data(:, 1));
set(handle, 'YData', data(:, 2));
if is3D
set(handle, 'ZData', data(:, 3));
end
end
% ==========================================================================
function [bottomLeft, topLeft, bottomRight, topRight] = corners2D(xLim, yLim)
% Determine the corners of the axes as defined by xLim and yLim
bottomLeft = [xLim(1), yLim(1)];
topLeft = [xLim(1), yLim(2)];
bottomRight = [xLim(2), yLim(1)];
topRight = [xLim(2), yLim(2)];
end
% ==========================================================================
function corners = corners3D(xLim, yLim, zLim)
% Determine the corners of the 3D axes as defined by xLim, yLim, and
% zLim
% Lower square of the cube
lowerBottomLeft = [xLim(1), yLim(1), zLim(1)];
lowerTopLeft = [xLim(1), yLim(2), zLim(1)];
lowerBottomRight = [xLim(2), yLim(1), zLim(1)];
lowerTopRight = [xLim(2), yLim(2), zLim(1)];
% Upper square of the cube
upperBottomLeft = [xLim(1), yLim(1), zLim(2)];
upperTopLeft = [xLim(1), yLim(2), zLim(2)];
upperBottomRight = [xLim(2), yLim(1), zLim(2)];
upperTopRight = [xLim(2), yLim(2), zLim(2)];
% Put the into one matrix
corners = [lowerBottomLeft;
lowerTopLeft;
lowerBottomRight;
lowerTopRight;
upperBottomLeft;
upperTopLeft;
upperBottomRight;
upperTopRight];
end
% ==========================================================================
function P = getProjectionMatrix(meta)
% Calculate the projection matrix from a 3D plot into the image plane
% Get the projection angle
[az, el] = view(meta.gca);
% Convert from degrees to radians.
az = az*pi/180;
el = el*pi/180;
% The transformation into the image plane is done in a two-step process.
% First: rotate around the z-axis by -az (in radians)
rotationZ = [ cos(-az) -sin(-az) 0 0
sin(-az) cos(-az) 0 0
0 0 1 0
0 0 0 1];
% Second: rotate around the x-axis by (el - pi/2) radians.
% NOTE: There are some trigonometric simplifications, as we use
% (el-pi/2)
% cos(x - pi/2) = sin(x)
% sin(x - pi/2) = -cos(x)
rotationX = [ 1 0 0 0
0 sin(el) cos(el) 0
0 -cos(el) sin(el) 0
0 0 0 1];
% Get the data aspect ratio. This is necessary, as the axes usually do
% not have the same scale (xRange~=yRange)
aspectRatio = get(meta.gca, 'DataAspectRatio');
scaleMatrix = diag([1./aspectRatio, 1]);
% Calculate the projection matrix
P = rotationX * rotationZ * scaleMatrix;
end
% =========================================================================
function [W, H] = getWidthHeightInPixels(targetResolution)
% Retrieves target figure width and height in pixels
% TODO: If targetResolution is a scalar, W and H are determined
% differently on different environments (octave, local vs. Travis).
% It is unclear why, as this even happens, if `Units` and `Position`
% are matching. Could it be that the `set(gcf,'Units','Inches')` is not
% taken into consideration for `Position`, directly after setting it?
% targetResolution is PPI
if isscalar(targetResolution)
% Query figure size in inches and convert W and H to target pixels
oldunits = get(gcf,'Units');
set(gcf,'Units','Inches');
figSizeIn = get(gcf,'Position');
W = figSizeIn(3) * targetResolution;
H = figSizeIn(4) * targetResolution;
set(gcf,'Units', oldunits) % restore original unit
% It is already in the format we want
else
W = targetResolution(1);
H = targetResolution(2);
end
end
% =========================================================================
function bool = isValidTargetResolution(val)
bool = isnumeric(val) && ~any(isnan(val)) && (isscalar(val) || numel(val) == 2);
end
% =========================================================================
function bool = isValidAxis(val)
bool = length(val) <= 3;
for i=1:length(val)
bool = bool && ...
(strcmpi(val(i), 'x') || ...
strcmpi(val(i), 'y') || ...
strcmpi(val(i), 'z'));
end
end
% ========================================================================
function normalizeAxis(handle, cmdOpts)
% Normalizes data from a given axis into the interval [0, 1]
% Warn about normalizeAxis being experimental
warning('cleanfigure:normalizeAxis', ...
'Normalization of axis data is experimental!');
for axis = cmdOpts.normalizeAxis(:)'
% Get the scale needed to set xyz-lim to [0, 1]
dateLimits = get(handle, [upper(axis), 'Lim']);
dateScale = 1/diff(dateLimits);
% Set the TickLabelMode to manual to preserve the labels
set(handle, [upper(axis), 'TickLabelMode'], 'manual');
% Project the ticks
ticks = get(handle, [upper(axis), 'Tick']);
ticks = (ticks - dateLimits(1))*dateScale;
% Set the data
set(handle, [upper(axis), 'Tick'], ticks);
set(handle, [upper(axis), 'Lim'], [0, 1]);
% Traverse the children
children = get(handle, 'Children');
for child = children(:)'
if isprop(child, [upper(axis), 'Data'])
% Get the data and transform it
data = get(child, [upper(axis), 'Data']);
data = (data - dateLimits(1))*dateScale;
% Set the data again
set(child, [upper(axis), 'Data'], data);
end
end
end
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
m2tUpdater.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/private/m2tUpdater.m
| 12,693 |
windows_1250
|
5cdcb942826889ea6018fe3febc897df
|
function m2tUpdater(about, verbose)
%UPDATER Auto-update matlab2tikz.
% Only for internal usage.
% Copyright (c) 2012--2014, Nico Schlömer <[email protected]>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% =========================================================================
fileExchangeUrl = about.website;
version = about.version;
mostRecentVersion = determineLatestRelease(version, fileExchangeUrl);
if askToUpgrade(mostRecentVersion, version, verbose)
tryToUpgrade(fileExchangeUrl, verbose);
userInfo(verbose, '');
end
end
% ==============================================================================
function shouldUpgrade = askToUpgrade(mostRecentVersion, version, verbose)
shouldUpgrade = false;
if ~isempty(mostRecentVersion)
userInfo(verbose, '**********************************************\n');
userInfo(verbose, 'New version (%s) available!\n', mostRecentVersion);
userInfo(verbose, '**********************************************\n');
warnAboutUpgradeImplications(version, mostRecentVersion, verbose);
askToShowChangelog(version);
reply = input(' *** Would you like to upgrade? y/n [n]:','s');
shouldUpgrade = ~isempty(reply) && strcmpi(reply(1),'y');
if ~shouldUpgrade
userInfo(verbose, ['\nTo disable the self-updater in the future, add ' ...
'"''checkForUpdates'',false" to the parameters.\n'] );
end
end
end
% ==============================================================================
function tryToUpgrade(fileExchangeUrl, verbose)
% Download the files and unzip its contents into two folders
% above the folder that contains the current script.
% This assumes that the file structure is something like
%
% src/matlab2tikz.m
% src/[...]
% src/private/m2tUpdater
% src/private/[...]
% AUTHORS
% ChangeLog
% [...]
%
% on the hard drive and the zip file. In particular, this assumes
% that the folder on the hard drive is writable by the user
% and that matlab2tikz.m is not symlinked from some other place.
pathstr = fileparts(mfilename('fullpath'));
targetPath = fullfile(pathstr, '..', '..');
% Let the user know where the .zip is downloaded to
userInfo(verbose, 'Downloading and unzipping to ''%s'' ...', targetPath);
% Try upgrading
try
% List current folder structure. Will use last for cleanup
currentFolderFiles = rdirfiles(targetPath);
% The FEX now forwards the download request to Github.
% Go through the forwarding to update the download count and
% unzip
html = urlread([fileExchangeUrl, '?download=true']);
expression = '(?<=\<a href=")[\w\-\/:\.]+(?=">redirected)';
url = regexp(html, expression,'match','once');
unzippedFiles = unzip(url, targetPath);
% The folder structure is additionally packed into the
% 'MATLAB Search Path' folder defined in FEX. Retrieve the
% top folder name
tmp = strrep(unzippedFiles,[targetPath, filesep],'');
tmp = regexp(tmp, filesep,'split','once');
tmp = cat(1,tmp{:});
topZipFolder = unique(tmp(:,1));
% If packed into the top folder, overwrite files into m2t
% main directory
if numel(topZipFolder) == 1
unzippedFilesTarget = fullfile(targetPath, tmp(:,2));
for ii = 1:numel(unzippedFiles)
movefile(unzippedFiles{ii}, unzippedFilesTarget{ii})
end
% Add topZipFolder to current folder structure
currentFolderFiles = [currentFolderFiles; fullfile(targetPath, topZipFolder{1})];
end
cleanupOldFiles(currentFolderFiles, unzippedFilesTarget);
userInfo(verbose, 'Upgrade has completed successfully.');
catch
err = lasterror(); %#ok needed for Octave
userInfo(verbose, ...
['Upgrade has failed with error message "%s".\n', ...
'Please install the latest version manually from %s !'], ...
err.message, fileExchangeUrl);
end
end
% ==============================================================================
function cleanupOldFiles(currentFolderFiles, unzippedFilesTarget)
% Delete files that were there in the old folder, but that are no longer
% present in the new release.
newFolderStructure = [getFolders(unzippedFilesTarget); unzippedFilesTarget];
deleteFolderFiles = setdiff(currentFolderFiles, newFolderStructure);
for ii = 1:numel(deleteFolderFiles)
x = deleteFolderFiles{ii};
if exist(x, 'dir') == 7
% First check for directories since
% `exist(x, 'file')` also checks for directories!
rmdir(x,'s');
elseif exist(x, 'file') == 2
delete(x);
end
end
end
% ==============================================================================
function mostRecentVersion = determineLatestRelease(version, fileExchangeUrl)
% Read in the Github releases page
url = 'https://github.com/matlab2tikz/matlab2tikz/releases/';
try
html = urlread(url);
catch %#ok
% Couldn't load the URL -- never mind.
html = '';
warning('m2tUpdate:siteNotFound', ...
['Cannot determine the latest version.\n', ...
'Either your internet is down or something went wrong.\n', ...
'You might want to check for updates by hand at %s.\n'], ...
fileExchangeUrl);
end
% Parse tag names which are the version number in the format ##.##.##
% It assumes that releases will always be tagged with the version number
expression = '(?<=matlab2tikz\/matlab2tikz\/releases\/tag\/)\d+\.\d+\.\d+';
tags = regexp(html, expression, 'match');
ntags = numel(tags);
% Keep only new releases
inew = false(ntags,1);
for ii = 1:ntags
inew(ii) = isVersionBelow(version, tags{ii});
end
nnew = nnz(inew);
% One new release
if nnew == 1
mostRecentVersion = tags{inew};
% Several new release, pick latest
elseif nnew > 1
tags = tags(inew);
tagnum = zeros(nnew,1);
for ii = 1:nnew
tagnum(ii) = [10000,100,1] * versionArray(tags{ii});
end
[~, imax] = max(tagnum);
mostRecentVersion = tags{imax};
% No new
else
mostRecentVersion = '';
end
end
% ==============================================================================
function askToShowChangelog(currentVersion)
% Asks whether the user wants to see the changelog and then shows it.
reply = input(' *** Would you like to see the changelog? y/n [y]:' ,'s');
shouldShow = isempty(reply) || ~strcmpi(reply(1),'n') ;
if shouldShow
fprintf(1, '\n%s\n', changelogUntilVersion(currentVersion));
end
end
% ==============================================================================
function changelog = changelogUntilVersion(currentVersion)
% This function retrieves the chunk of the changelog until the current version.
URL = 'https://github.com/matlab2tikz/matlab2tikz/raw/master/CHANGELOG.md';
changelog = urlread(URL);
currentVersion = versionString(currentVersion);
% Header is "# YYYY-MM-DD Version major.minor.patch [Manager](email)"
% Just match for the part until the version number. Here, we're actually
% matching a tiny bit too broad due to the periods in the version number
% but the outcome should be the same if we keep the changelog format
% identical.
pattern = ['\#\s*[\d-]+\s*Version\s*' currentVersion];
idxVersion = regexpi(changelog, pattern);
if ~isempty(idxVersion)
changelog = changelog(1:idxVersion-1);
else
% Just show the whole changelog if we don't find the old version.
end
end
% ==============================================================================
function warnAboutUpgradeImplications(currentVersion, latestVersion, verbose)
% This warns the user about the implications of upgrading as dictated by
% Semantic Versioning.
switch upgradeSize(currentVersion, latestVersion);
case 'major'
% The API might have changed in a backwards incompatible way.
userInfo(verbose, 'This is a MAJOR upgrade!\n');
userInfo(verbose, ' - New features may have been introduced.');
userInfo(verbose, ' - Some old code/options may no longer work!\n');
case 'minor'
% The API may NOT have changed in a backwards incompatible way.
userInfo(verbose, 'This is a MINOR upgrade.\n');
userInfo(verbose, ' - New features may have been introduced.');
userInfo(verbose, ' - Some options may have been deprecated.');
userInfo(verbose, ' - Old code should continue to work but might produce warnings.\n');
case 'patch'
% No new functionality is introduced
userInfo(verbose, 'This is a PATCH.\n');
userInfo(verbose, ' - Only bug fixes are included in this upgrade.');
userInfo(verbose, ' - Old code should continue to work as before.')
end
userInfo(verbose, 'Please check the changelog for detailed information.\n');
userWarn(verbose, '\n!! By upgrading you will lose any custom changes !!\n');
end
% ==============================================================================
function cls = upgradeSize(currentVersion, latestVersion)
% Determines whether the upgrade is major, minor or a patch.
currentVersion = versionArray(currentVersion);
latestVersion = versionArray(latestVersion);
description = {'major', 'minor', 'patch'};
for ii = 1:numel(description)
if latestVersion(ii) > currentVersion(ii)
cls = description{ii};
return
end
end
cls = 'unknown';
end
% ==============================================================================
function userInfo(verbose, message, varargin)
% Display information (i.e. to stdout)
if verbose
userPrint(1, message, varargin{:});
end
end
function userWarn(verbose, message, varargin)
% Display warnings (i.e. to stderr)
if verbose
userPrint(2, message, varargin{:});
end
end
function userPrint(fid, message, varargin)
% Print messages (info/warnings) to a stream/file.
mess = sprintf(message, varargin{:});
% Replace '\n' by '\n *** ' and print.
mess = strrep( mess, sprintf('\n'), sprintf('\n *** ') );
fprintf(fid, ' *** %s\n', mess );
end
% =========================================================================
function list = rdirfiles(rootdir)
% Recursive files listing
s = dir(rootdir);
list = {s.name}';
% Exclude .git, .svn, . and ..
[list, idx] = setdiff(list, {'.git','.svn','.','..'});
% Add root
list = fullfile(rootdir, list);
% Loop for sub-directories
pdir = find([s(idx).isdir]);
for ii = pdir
list = [list; rdirfiles(list{ii})]; %#ok<AGROW>
end
% Drop directories
list(pdir) = [];
end
% =========================================================================
function list = getFolders(list)
% Extract the folder structure from a list of files and folders
for ii = 1:numel(list)
if exist(list{ii},'file') == 2
list{ii} = fileparts(list{ii});
end
end
list = unique(list);
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
formatWhitespace.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/src/dev/formatWhitespace.m
| 3,119 |
utf_8
|
f28d2958f20ad3dad9e278cff4cee942
|
function formatWhitespace(filename)
% FORMATWHITESPACE Formats whitespace and indentation of a document
%
% FORMATWHITESPACE(FILENAME)
% Indents currently active document if FILENAME is empty or not
% specified. FILENAME must be the name of an open document in the
% editor.
%
% Rules:
% - Smart-indent with all function indent option
% - Indentation is 4 spaces
% - Remove whitespace in empty lines
% - Preserve indentantion after line continuations, i.e. ...
%
import matlab.desktop.editor.*
if nargin < 1, filename = ''; end
d = getDoc(filename);
oldLines = textToLines(d.Text);
% Smart indent as AllFunctionIndent
% Using undocumented feature from http://undocumentedmatlab.com/blog/changing-system-preferences-programmatically
editorProp = 'EditorMFunctionIndentType';
oldVal = com.mathworks.services.Prefs.getStringPref(editorProp);
com.mathworks.services.Prefs.setStringPref(editorProp, 'AllFunctionIndent');
restoreSettings = onCleanup(@() com.mathworks.services.Prefs.setStringPref(editorProp, oldVal));
d.smartIndentContents()
% Preserve crafted continuations of line
lines = textToLines(d.Text);
iContinuation = ~cellfun('isempty',strfind(lines, '...'));
iComment = ~cellfun('isempty',regexp(lines, '^ *%([^%]|$)','once'));
pAfterDots = find(iContinuation & ~iComment)+1;
for ii = 1:numel(pAfterDots)
% Carry over the change in space due to smart-indenting from the
% first continuation line to the last
p = pAfterDots(ii);
nWhiteBefore = find(~isspace(oldLines{p-1}),1,'first');
nWhiteAfter = find(~isspace(lines{p-1}),1,'first');
df = nWhiteAfter - nWhiteBefore;
if df > 0
lines{p} = [blanks(df) oldLines{p}];
elseif df < 0
df = min(abs(df)+1, find(~isspace(oldLines{p}),1,'first'));
lines{p} = oldLines{p}(df:end);
else
lines{p} = oldLines{p};
end
end
% Remove whitespace lines
idx = cellfun('isempty',regexp(lines, '[^ \t\n]','once'));
lines(idx) = {''};
d.Text = linesToText(lines);
end
function d = getDoc(filename)
import matlab.desktop.editor.*
if ~ischar(filename)
error('formatWhitespace:charFilename','The FILENAME should be a char.')
end
try
isEditorAvailable();
catch
error('formatWhitespace:noEditorApi','Check that the Editor API is available.')
end
if isempty(filename)
d = getActive();
else
% TODO: open file if it isn't open in the editor already
d = findOpenDocument(filename);
try
[~,filenameFound] = fileparts(d.Filename);
catch
filenameFound = '';
end
isExactMatch = strcmp(filename, filenameFound);
if ~isExactMatch
error('formatWhitespace:filenameNotFound','Filename "%s" not found in the editor.', filename)
end
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
makeLatexReport.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/makeLatexReport.m
| 9,713 |
utf_8
|
11fa5570feeb4f29440ea1e539314532
|
function makeLatexReport(status, output)
% generate a LaTeX report
%
%
if ~exist('output','var')
output = m2troot('test','output','current');
end
% first, initialize the tex output
SM = StreamMaker();
stream = SM.make(fullfile(output, 'acid.tex'), 'w');
texfile_init(stream);
printFigures(stream, status);
printSummaryTable(stream, status);
printErrorMessages(stream, status);
printEnvironmentInfo(stream, status);
texfile_finish(stream);
end
% =========================================================================
function texfile_init(stream)
stream.print(['\\documentclass[landscape]{scrartcl}\n' , ...
'\\pdfminorversion=6\n\n' , ...
'\\usepackage{amsmath} %% required for $\\text{xyz}$\n\n', ...
'\\usepackage{hyperref}\n' , ...
'\\usepackage{graphicx}\n' , ...
'\\usepackage{epstopdf}\n' , ...
'\\usepackage{tikz}\n' , ...
'\\usetikzlibrary{plotmarks}\n\n' , ...
'\\usepackage{pgfplots}\n' , ...
'\\pgfplotsset{compat=newest}\n\n' , ...
'\\usepackage[margin=0.5in]{geometry}\n' , ...
'\\newlength\\figurewidth\n' , ...
'\\setlength\\figurewidth{0.4\\textwidth}\n\n' , ...
'\\begin{document}\n\n']);
end
% =========================================================================
function texfile_finish(stream)
stream.print('\\end{document}');
end
% =========================================================================
function printFigures(stream, status)
for k = 1:length(status)
texfile_addtest(stream, status{k});
end
end
% =========================================================================
function printSummaryTable(stream, status)
texfile_tab_completion_init(stream)
for k = 1:length(status)
stat = status{k};
testNumber = stat.index;
% Break table up into pieces if it gets too long for one page
%TODO: use booktabs instead
%TODO: maybe just write a function to construct the table at once
% from a cell array (see makeTravisReport for GFM counterpart)
if ~mod(k,35)
texfile_tab_completion_finish(stream);
texfile_tab_completion_init(stream);
end
stream.print('%d & \\texttt{%s}', testNumber, name2tex(stat.function));
if stat.skip
stream.print(' & --- & skipped & ---');
else
for err = [stat.plotStage.error, ...
stat.saveStage.error, ...
stat.tikzStage.error]
if err
stream.print(' & \\textcolor{red}{failed}');
else
stream.print(' & \\textcolor{green!50!black}{passed}');
end
end
end
stream.print(' \\\\\n');
end
texfile_tab_completion_finish(stream);
end
% =========================================================================
function printErrorMessages(stream, status)
if errorHasOccurred(status)
stream.print('\\section*{Error messages}\n\\scriptsize\n');
for k = 1:length(status)
stat = status{k};
testNumber = stat.index;
if isempty(stat.plotStage.message) && ...
isempty(stat.saveStage.message) && ...
isempty(stat.tikzStage.message)
continue % No error messages for this test case
end
stream.print('\n\\subsection*{Test case %d: \\texttt{%s}}\n', testNumber, name2tex(stat.function));
print_verbatim_information(stream, 'Plot generation', stat.plotStage.message);
print_verbatim_information(stream, 'PDF generation' , stat.saveStage.message);
print_verbatim_information(stream, 'matlab2tikz' , stat.tikzStage.message);
end
stream.print('\n\\normalsize\n\n');
end
end
% =========================================================================
function printEnvironmentInfo(stream, status)
[env,versionString] = getEnvironment();
testsuites = unique(cellfun(@(s) func2str(s.testsuite) , status, ...
'UniformOutput', false));
testsuites = name2tex(m2tstrjoin(testsuites, ', '));
stream.print(['\\newpage\n',...
'\\begin{tabular}{ll}\n',...
' Suite & ' testsuites ' \\\\ \n', ...
' Created & ' datestr(now) ' \\\\ \n', ...
' OS & ' OSVersion ' \\\\ \n',...
' ' env ' & ' versionString ' \\\\ \n', ...
VersionControlIdentifier, ...
' TikZ & \\expandafter\\csname [email protected]\\endcsname \\\\ \n',...
' Pgfplots & \\expandafter\\csname [email protected]\\endcsname \\\\ \n',...
'\\end{tabular}\n']);
end
% =========================================================================
function print_verbatim_information(stream, title, contents)
if ~isempty(contents)
stream.print(['\\subsubsection*{%s}\n', ...
'\\begin{verbatim}\n%s\\end{verbatim}\n'], ...
title, contents);
end
end
% =========================================================================
function texfile_addtest(stream, status)
% Actually add the piece of LaTeX code that'll later be used to display
% the given test.
if ~status.skip
ref_error = status.plotStage.error;
gen_error = status.tikzStage.error;
ref_file = status.saveStage.texReference;
gen_file = status.tikzStage.pdfFile;
stream.print(...
['\\begin{figure}\n' , ...
' \\centering\n' , ...
' \\begin{tabular}{cc}\n' , ...
' %s & %s \\\\\n' , ...
' reference rendering & generated\n' , ...
' \\end{tabular}\n' , ...
' \\caption{%s \\texttt{%s}, \\texttt{%s(%d)}.%s}\n', ...
'\\end{figure}\n' , ...
'\\clearpage\n\n'],...
include_figure(ref_error, 'includegraphics', ref_file), ...
include_figure(gen_error, 'includegraphics', gen_file), ...
status.description, ...
name2tex(status.function), name2tex(status.testsuite), status.index, ...
formatIssuesForTeX(status.issues));
end
end
% =========================================================================
function str = include_figure(errorOccured, command, filename)
if errorOccured
str = sprintf(['\\tikz{\\draw[red,thick] ', ...
'(0,0) -- (\\figurewidth,\\figurewidth) ', ...
'(0,\\figurewidth) -- (\\figurewidth,0);}']);
else
switch command
case 'includegraphics'
strFormat = '\\includegraphics[width=\\figurewidth]{%s}';
case 'input'
strFormat = '\\input{%s}';
otherwise
error('Matlab2tikz_acidtest:UnknownFigureCommand', ...
'Unknown figure command "%s"', command);
end
str = sprintf(strFormat, filename);
end
end
% =========================================================================
function texfile_tab_completion_init(stream)
stream.print(['\\clearpage\n\n' , ...
'\\begin{table}\n' , ...
'\\centering\n' , ...
'\\caption{Test case completion summary}\n' , ...
'\\begin{tabular}{rlccc}\n' , ...
'No. & Test case & Plot & PDF & TikZ \\\\\n' , ...
'\\hline\n']);
end
% =========================================================================
function texfile_tab_completion_finish(stream)
stream.print( ['\\end{tabular}\n' , ...
'\\end{table}\n\n' ]);
end
% =========================================================================
function texName = name2tex(matlabIdentifier)
% convert a MATLAB identifier/function handle to a TeX string
if isa(matlabIdentifier, 'function_handle')
matlabIdentifier = func2str(matlabIdentifier);
end
texName = strrep(matlabIdentifier, '_', '\_');
end
% =========================================================================
function str = formatIssuesForTeX(issues)
% make links to GitHub issues for the LaTeX output
issues = issues(:)';
if isempty(issues)
str = '';
return
end
BASEURL = 'https://github.com/matlab2tikz/matlab2tikz/issues/';
SEPARATOR = sprintf(' \n');
strs = arrayfun(@(n) sprintf(['\\href{' BASEURL '%d}{\\#%d}'], n,n), issues, ...
'UniformOutput', false);
strs = [strs; repmat({SEPARATOR}, 1, numel(strs))];
str = sprintf('{\\color{blue} \\texttt{%s}}', [strs{:}]);
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
makeTapReport.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/makeTapReport.m
| 2,252 |
utf_8
|
473406d1fab6a34f9edfe7bc4faf4241
|
function makeTapReport(status, varargin)
% Makes a Test Anything Protocol report
%
% This function produces a testing report of HEADLESS tests for
% display on Jenkins (or any other TAP-compatible system)
%
% MAKETAPREPORT(status) produces the report from the `status` output of
% `testHeadless`.
%
% MAKETAPREPORT(status, 'stream', FID, ...) changes the filestream to use
% to output the report to. (Default: 1 (stdout)).
%
% TAP Specification: https://testanything.org
%
% See also: testHeadless, makeTravisReport, makeLatexReport
%% Parse input arguments
SM = StreamMaker();
ipp = m2tInputParser();
ipp = ipp.addRequired(ipp, 'status', @iscell);
ipp = ipp.addParamValue(ipp, 'stream', 1, SM.isStream);
ipp = ipp.parse(ipp, status, varargin{:});
arg = ipp.Results;
%% Construct stream
stream = SM.make(arg.stream, 'w');
%% build report
printTAPVersion(stream);
printTAPPlan(stream, status);
for iStatus = 1:numel(status)
printTAPReport(stream, status{iStatus}, iStatus);
end
end
% ==============================================================================
function printTAPVersion(stream)
% prints the TAP version
stream.print('TAP version 13\n');
end
function printTAPPlan(stream, statuses)
% prints the TAP test plan
firstTest = 1;
lastTest = numel(statuses);
stream.print('%d..%d\n', firstTest, lastTest);
end
function printTAPReport(stream, status, testNum)
% prints a TAP test case report
message = status.function;
if hasTestFailed(status)
result = 'not ok';
else
result = 'ok';
end
directives = getTAPDirectives(status);
stream.print('%s %d %s %s\n', result, testNum, message, directives);
%TODO: we can provide more information on the failure using YAML syntax
end
function directives = getTAPDirectives(status)
% add TAP directive (a todo or skip) to the test directives
directives = {};
if status.skip
directives{end+1} = '# SKIP skipped';
end
if status.unreliable
directives{end+1} = '# TODO unreliable';
end
directives = strtrim(m2tstrjoin(directives, ' '));
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
testGraphical.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/testGraphical.m
| 1,535 |
utf_8
|
98943d624f8c47a566e9393514379b88
|
function [ status ] = testGraphical( varargin )
%TESTGRAPHICAL Runs the M2T test suite to produce graphical output
%
% This is quite a thin wrapper around testMatlab2tikz to run the test suite to
% produce a PDF side-by-side report.
%
% Its allowed arguments are the same as those of testMatlab2tikz.
%
% Usage:
%
% status = testGraphical(...) % gives programmatical access to the data
%
% testGraphical(...); % automatically invokes makeLatexReport afterwards
%
% See also: testMatlab2tikz, testHeadless, makeLatexReport
[state] = initializeGlobalState();
finally_restore_state = onCleanup(@() restoreGlobalState(state));
[status, args] = testMatlab2tikz('actionsToExecute', @actionsToExecute, ...
varargin{:});
if nargout == 0
makeLatexReport(status, args.output);
end
end
% ==============================================================================
function status = actionsToExecute(status, ipp)
status = execute_plot_stage(status, ipp);
if status.skip
return
end
status = execute_save_stage(status, ipp);
status = execute_tikz_stage(status, ipp);
%status = execute_hash_stage(status, ipp); %cannot work with files in
%standalone mode!
status = execute_type_stage(status, ipp);
if ~status.closeall && ~isempty(status.plotStage.fig_handle)
close(status.plotStage.fig_handle);
else
close all;
end
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
testHeadless.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/testHeadless.m
| 2,211 |
utf_8
|
21593a779ad2f668bd365170135646c1
|
function [ status ] = testHeadless( varargin )
%TESTGRAPHICAL Runs the M2T test suite without graphical output
%
% This is quite a thin wrapper around testMatlab2tikz to run the test suite to
% produce a textual report and checks for regressions by checking the MD5 hash
% of the output
%
% Its allowed arguments are the same as those of testMatlab2tikz.
%
% Usage:
%
% status = TESTHEADLESS(...) % gives programmatical access to the data
%
% TESTHEADLESS(...); % automatically invokes makeTravisReport afterwards
%
% See also: testMatlab2tikz, testGraphical, makeTravisReport
% The width and height are specified to circumvent different DPIs in developer
% machines. The float format reduces the probability that numerical differences
% in the order of numerical precision disrupt the output.
extraOptions = {'width' ,'\figureWidth', ...
'height','\figureHeight',...
'floatFormat', '%4g', ... % see #604
'extraCode',{ ...
'\newlength\figureHeight \setlength{\figureHeight}{6cm}', ...
'\newlength\figureWidth \setlength{\figureWidth}{10cm}'}
};
[state] = initializeGlobalState();
finally_restore_state = onCleanup(@() restoreGlobalState(state));
status = testMatlab2tikz('extraOptions', extraOptions, ...
'actionsToExecute', @actionsToExecute, ...
varargin{:});
if nargout == 0
makeTravisReport(status);
end
end
% ==============================================================================
function status = actionsToExecute(status, ipp)
status = execute_plot_stage(status, ipp);
if status.skip
return
end
status = execute_tikz_stage(status, ipp);
status = execute_hash_stage(status, ipp);
status = execute_type_stage(status, ipp);
if ~status.closeall && ~isempty(status.plotStage.fig_handle)
try
close(status.plotStage.fig_handle);
catch
close('all');
end
else
close all;
end
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
codeReport.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/codeReport.m
| 9,687 |
utf_8
|
04a4f77e42910607770ceb578e223006
|
function [ report ] = codeReport( varargin )
%CODEREPORT Builds a report of the code health
%
% This function generates a Markdown report on the code health. At the moment
% this is limited to the McCabe (cyclomatic) complexity of a function and its
% subfunctions.
%
% This makes use of |checkcode| in MATLAB.
%
% Usage:
%
% CODEREPORT('function', functionName) to determine which function is
% analyzed. (default: matlab2tikz)
%
% CODEREPORT('complexityThreshold', integer ) to set above which complexity, a
% function is added to the report (default: 10)
%
% CODEREPORT('stream', stream) to set to which stream/file to output the report
% (default: 1, i.e. stdout). The stream is used only when no output argument
% for `codeReport` is specified!.
%
% See also: checkcode, mlint
SM = StreamMaker();
%% input options
ipp = m2tInputParser();
ipp = ipp.addParamValue(ipp, 'function', 'matlab2tikz', @ischar);
ipp = ipp.addParamValue(ipp, 'complexityThreshold', 10, @isnumeric);
ipp = ipp.addParamValue(ipp, 'stream', 1, SM.isStream);
ipp = ipp.parse(ipp, varargin{:});
stream = SM.make(ipp.Results.stream, 'w');
%% generate report data
data = checkcode(ipp.Results.function,'-cyc','-struct');
[complexityAll, mlintMessages] = splitCycloComplexity(data);
%% analyze cyclomatic complexity
categorizeComplexity = @(x) categoryOfComplexity(x, ...
ipp.Results.complexityThreshold, ...
ipp.Results.function);
complexityAll = arrayfun(@parseCycloComplexity, complexityAll);
complexityAll = arrayfun(categorizeComplexity, complexityAll);
complexity = filter(complexityAll, @(x) strcmpi(x.category, 'Bad'));
complexity = sortBy(complexity, 'line', 'ascend');
complexity = sortBy(complexity, 'complexity', 'descend');
[complexityStats] = complexityStatistics(complexityAll);
%% analyze other messages
%TODO: handle all mlint messages and/or other metrics of the code
%% format report
dataStr = complexity;
dataStr = arrayfun(@(d) mapField(d, 'function', @markdownInlineCode), dataStr);
if ~isempty(dataStr)
dataStr = addFooterRow(dataStr, 'complexity', @sum, {'line',0, 'function',bold('Total')});
end
dataStr = arrayfun(@(d) mapField(d, 'line', @integerToString), dataStr);
dataStr = arrayfun(@(d) mapField(d, 'complexity', @integerToString), dataStr);
report = makeTable(dataStr, {'function', 'complexity'}, ...
{'Function', 'Complexity'});
%% command line usage
if nargout == 0
if ismember(stream.name, {'stdout','stderr'})
stream.print('%s\n', codelinks(report, ipp.Results.function));
else
stream.print('%s\n', report);
end
figure('name',sprintf('Complexity statistics of %s', ipp.Results.function));
h = statisticsPlot(complexityStats, 'Complexity', 'Number of functions');
for hh = h
plot(hh, [1 1]*ipp.Results.complexityThreshold, ylim(hh), ...
'k--','DisplayName','Threshold');
end
legend(h(1),'show','Location','NorthEast');
clear report
end
end
%% CATEGORIZATION ==============================================================
function [complexity, others] = splitCycloComplexity(list)
% splits codereport into McCabe complexity and others
filter = @(l) ~isempty(strfind(l.message, 'McCabe complexity'));
idxComplexity = arrayfun(filter, list);
complexity = list( idxComplexity);
others = list(~idxComplexity);
end
function [data] = categoryOfComplexity(data, threshold, mainFunc)
% categorizes the complexity as "Good", "Bad" or "Accepted"
TOKEN = '#COMPLEX'; % token to signal allowed complexity
try %#ok
helpStr = help(sprintf('%s>%s', mainFunc, data.function));
if ~isempty(strfind(helpStr, TOKEN))
data.category = 'Accepted';
return;
end
end
if data.complexity > threshold
data.category = 'Bad';
else
data.category = 'Good';
end
end
%% PARSING =====================================================================
function [out] = parseCycloComplexity(in)
% converts McCabe complexity report strings into a better format
out = regexp(in.message, ...
'The McCabe complexity of ''(?<function>[A-Za-z0-9_]+)'' is (?<complexity>[0-9]+).', ...
'names');
out.complexity = str2double(out.complexity);
out.line = in.line;
end
%% DATA PROCESSING =============================================================
function selected = filter(list, filterFunc)
% filters an array according to a binary function
idx = logical(arrayfun(filterFunc, list));
selected = list(idx);
end
function [data] = mapField(data, field, mapping)
data.(field) = mapping(data.(field));
end
function sorted = sortBy(list, fieldName, mode)
% sorts a struct array by a single field
% extra arguments are as for |sort|
values = arrayfun(@(m)m.(fieldName), list);
[dummy, idxSorted] = sort(values(:), 1, mode); %#ok
sorted = list(idxSorted);
end
function [stat] = complexityStatistics(list)
% calculate some basic statistics of the complexities
stat.values = arrayfun(@(c)(c.complexity), list);
stat.binCenter = sort(unique(stat.values));
categoryPerElem = {list.category};
stat.categories = unique(categoryPerElem);
nCategories = numel(stat.categories);
groupedHist = zeros(numel(stat.binCenter), nCategories);
for iCat = 1:nCategories
category = stat.categories{iCat};
idxCat = ismember(categoryPerElem, category);
groupedHist(:,iCat) = hist(stat.values(idxCat), stat.binCenter);
end
stat.histogram = groupedHist;
stat.median = median(stat.values);
end
function [data] = addFooterRow(data, column, func, otherFields)
% adds a footer row to data table based on calculations of a single column
footer = data(end);
for iField = 1:2:numel(otherFields)
field = otherFields{iField};
value = otherFields{iField+1};
footer.(field) = value;
end
footer.(column) = func([data(:).(column)]);
data(end+1) = footer;
end
%% FORMATTING ==================================================================
function str = integerToString(value)
% convert integer to string
str = sprintf('%d',value);
end
function str = markdownInlineCode(str)
% format as inline code for markdown
str = sprintf('`%s`', str);
end
function str = makeTable(data, fields, header)
% make a markdown table from struct array
nData = numel(data);
str = '';
if nData == 0
return; % empty input
end
%TODO: use gfmTable from makeTravisReport instead to do the formatting
% determine column sizes
nFields = numel(fields);
table = cell(nFields, nData);
columnWidth = zeros(1,nFields);
for iField = 1:nFields
field = fields{iField};
table(iField, :) = {data(:).(field)};
columnWidth(iField) = max(cellfun(@numel, table(iField, :)));
end
columnWidth = max(columnWidth, cellfun(@numel, header));
columnWidth = columnWidth + 2; % empty space left and right
columnWidth([1,end]) = columnWidth([1,end]) - 1; % except at the edges
% format table inside cell array
table = [header; table'];
for iField = 1:nFields
FORMAT = ['%' int2str(columnWidth(iField)) 's'];
for jData = 1:size(table, 1)
table{jData, iField} = strjust(sprintf(FORMAT, ...
table{jData, iField}), 'center');
end
end
% insert separator
table = [table(1,:)
arrayfun(@(n) repmat('-',1,n), columnWidth, 'UniformOutput',false)
table(2:end,:)]';
% convert cell array to string
FORMAT = ['%s' repmat('|%s', 1,nFields-1) '\n'];
str = sprintf(FORMAT, table{:});
end
function str = codelinks(str, functionName)
% replaces inline functions with clickable links in MATLAB
str = regexprep(str, '`([A-Za-z0-9_]+)`', ...
['`<a href="matlab:edit ' functionName '>$1">$1</a>`']);
%NOTE: editing function>subfunction will focus on that particular subfunction
% in the editor (this also works for the main function)
end
function str = bold(str)
str = ['**' str '**'];
end
%% PLOTTING ====================================================================
function h = statisticsPlot(stat, xLabel, yLabel)
% plot a histogram and box plot
nCategories = numel(stat.categories);
colors = colorscheme;
h(1) = subplot(5,1,1:4);
hold all;
hb = bar(stat.binCenter, stat.histogram, 'stacked');
for iCat = 1:nCategories
category = stat.categories{iCat};
set(hb(iCat), 'DisplayName', category, 'FaceColor', colors.(category), ...
'LineStyle','none');
end
%xlabel(xLabel);
ylabel(yLabel);
h(2) = subplot(5,1,5);
hold all;
boxplot(stat.values,'orientation','horizontal',...
'boxstyle', 'outline', ...
'symbol', 'o', ...
'colors', colors.All);
xlabel(xLabel);
xlims = [min(stat.binCenter)-1 max(stat.binCenter)+1];
c = 1;
ylims = (ylim(h(2)) - c)/3 + c;
set(h,'XTickMode','manual','XTick',stat.binCenter,'XLim',xlims);
set(h(1),'XTickLabel','');
set(h(2),'YTickLabel','','YLim',ylims);
linkaxes(h, 'x');
end
function colors = colorscheme()
% recognizable color scheme for the categories
colors.All = [ 0 113 188]/255;
colors.Good = [118 171 47]/255;
colors.Bad = [161 19 46]/255;
colors.Accepted = [236 176 31]/255;
end
|
github
|
ga96jul/Bachelarbeit-master
|
saveHashTable.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/saveHashTable.m
| 6,769 |
utf_8
|
b5bd806af103238d79cbff4578d7e8ce
|
function saveHashTable(status, varargin)
% SAVEHASHTABLE saves the references hashes for the Matlab2Tikz tests
%
% Usage:
% SAVEHASHTABLE(status)
%
% SAVEHASHTABLE(status, 'dryrun', BOOL, ...) determines whether or not to
% write the constructed hash table to file (false) or to stdout (true).
% Default: false
%
% SAVEHASHTABLE(status, 'removedTests', CHAR, ...) specifies which action to
% execute on "removed tests" (i.e. test that have a hash recorded in the file,
% but which are not present in `status`). Three values are possible:
% - 'ask' (default): Ask what to do for each such test.
% - 'remove': Remove the test from the file.
% This is appropriate if the test has been removed from the suite.
% - 'keep': Keep the test hash in the file.
% This is appropriate when the test has not executed all tests.
%
% Inputs:
% - status: output cell array of the testing functions
%
% See also: runMatlab2TikzTests, testMatlab2tikz
ipp = m2tInputParser();
ipp = ipp.addRequired(ipp, 'status', @iscell);
ipp = ipp.addParamValue(ipp, 'dryrun', false, @islogical);
ipp = ipp.addParamValue(ipp, 'removedTests', 'ask', @isValidAction);
ipp = ipp.parse(ipp, status, varargin{:});
%% settings
suite = status{1}.testsuite; %TODO: handle multiple test suites in a single array
filename = hashTableName(suite);
READFORMAT = '%s : %s';
WRITEFORMAT = [READFORMAT '\n'];
%% process the hash table
oldHashes = readHashesFromFile(filename);
newHashes = updateHashesFromStatus(oldHashes, status);
writeHashesToFile(filename, newHashes);
% --------------------------------------------------------------------------
function hashes = updateHashesFromStatus(hashes, status)
% update hashes from the test results in status
oldFunctions = fieldnames(hashes);
newFunctions = cellfun(@(s) s.function, status, 'UniformOutput', false);
% add hashes from all executed tests
for iFunc = 1:numel(status)
S = status{iFunc};
thisFunc = S.function;
thisHash = '';
if isfield(S.hashStage,'found')
thisHash = S.hashStage.found;
elseif S.skip
if isfield(hashes, thisFunc)
% Test skipped, but reference hash present in file
% Probably this means that the developer doesn't have access
% to a certain toolbox.
warning('SaveHashTable:CannotUpdateSkippedTest', ...
'Test "%s" was skipped. Cannot update hash!',...
thisFunc);
else
% Test skipped and reference hash absent.
% Probably the test is skipped because something is tested
% that relies on HG1/HG2/Octace-specific features and we are
% in the wrong environment for the test.
end
else
warning('SaveHashTable:NoHashFound',...
'No hash found for "%s"!', thisFunc);
end
if ~isempty(thisHash)
hashes.(thisFunc) = thisHash;
end
end
% ask what to do with tests for which we have a hash, but no test results
removedTests = setdiff(oldFunctions, newFunctions);
if ~isempty(removedTests)
fprintf(1, 'Some tests in the file were not in the build status.\n');
end
for iTest = 1:numel(removedTests)
thisTest = removedTests{iTest};
action = askActionToPerformOnRemovedTest(thisTest);
switch action
case 'remove'
% useful for test that no longer exist
fprintf(1, 'Removed hash for "%s"\n', thisTest);
hashes = rmfield(hashes, thisTest);
case 'keep'
% useful when not all tests were executed by the tester
fprintf(1, 'Kept hash for "%s"\n', thisTest);
end
end
end
function action = askActionToPerformOnRemovedTest(testName)
% ask which action to carry out on a removed test
action = lower(ipp.Results.removedTests);
while ~isActualAction(action)
query = sprintf('Keep or remove "%s"? [Kr]:', testName);
answer = strtrim(input(query,'s'));
if isempty(answer) || strcmpi(answer(1), 'K')
action = 'keep';
elseif strcmpi(answer(1), 'R')
action = 'remove';
else
action = 'ask again';
% just keep asking until we get a reasonable answer
end
end
end
function writeHashesToFile(filename, hashes)
% write hashes to a file (or stdout when dry-running)
if ~ipp.Results.dryrun
fid = fopen(filename, 'w+');
finally_fclose_fid = onCleanup(@() fclose(fid));
else
fid = 1; % Use stdout to print everything
fprintf(fid, '\n\n Output: \n\n');
end
funcNames = sort(fieldnames(hashes));
for iFunc = 1:numel(funcNames)
func = funcNames{iFunc};
fprintf(fid, WRITEFORMAT, func, hashes.(func));
end
end
function hashes = readHashesFromFile(filename)
% read hashes from a file
if exist(filename,'file')
fid = fopen(filename, 'r');
finally_fclose_fid = onCleanup(@() fclose(fid));
data = textscan(fid, READFORMAT);
% data is now a cell array with 2 elements, each a (row) cell array
% - the first is all the function names
% - the second is all the hashes
% Transform `data` into {function1, hash1, function2, hash2, ...}'
% First step is to transpose the data concatenate both fields under
% each other. Since MATLAB indexing uses "column major order",
% traversing the concatenated array is in the order we want.
data = [data{:}]';
allValues = data(:)';
else
allValues = {};
end
hashes = struct(allValues{:});
end
end
% ==============================================================================
function bool = isValidAction(str)
% returns true for valid actions (keep/remove/ask) on "removedTests":
bool = ismember(lower(str), {'keep','remove','ask'});
end
function bool = isActualAction(str)
% returns true for actual actions (keep/remove) on "removedTests"
bool = ismember(lower(str), {'keep','remove'});
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
makeTravisReport.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/makeTravisReport.m
| 13,733 |
utf_8
|
9fc69f89ebc037cf2495966892207520
|
function [nErrors] = makeTravisReport(status, varargin)
% Makes a readable report for Travis/Github of test results
%
% This function produces a testing report of HEADLESS tests for
% display on GitHub and Travis.
%
% MAKETRAVISREPORT(status) produces the report from the `status` output of
% `testHeadless`.
%
% MAKETRAVISREPORT(status, 'stream', FID, ...) changes the filestream to use
% to output the report to. (Default: 1 (stdout)).
%
% MAKETRAVISREPORT(status, 'length', CHAR, ...) changes the report length.
% A few values are possible that cover different aspects in less/more detail.
% - 'default': all unreliable tests, failed & skipped tests and summary
% - 'short' : only show the brief summary
% - 'long' : all tests + summary
%
% See also: testHeadless, makeLatexReport
SM = StreamMaker();
%% Parse input arguments
ipp = m2tInputParser();
ipp = ipp.addRequired(ipp, 'status', @iscell);
ipp = ipp.addParamValue(ipp, 'stream', 1, SM.isStream);
ipp = ipp.addParamValue(ipp, 'length', 'default', @isReportLength);
ipp = ipp.parse(ipp, status, varargin{:});
arg = ipp.Results;
arg.length = lower(arg.length);
stream = SM.make(arg.stream, 'w');
%% transform status data into groups
S = splitStatuses(status);
%% build report
stream.print(gfmHeader(describeEnvironment));
reportUnreliableTests(stream, arg, S);
reportReliableTests(stream, arg, S);
displayTestSummary(stream, S);
%% set output arguments if needed
if nargout >= 1
nErrors = countNumberOfErrors(S.reliable);
end
end
% == INPUT VALIDATOR FUNCTIONS =================================================
function bool = isReportLength(val)
% validates the report length
bool = ismember(lower(val), {'default','short','long'});
end
% == GITHUB-FLAVORED MARKDOWN FUNCTIONS ========================================
function str = gfmTable(data, header, alignment)
% Construct a Github-flavored Markdown table
%
% Arguments:
% - data: nRows x nCols cell array that represents the data
% - header: cell array with the (nCol) column headers
% - alignment: alignment specification per column
% * 'l': left-aligned (default)
% * 'c': centered
% * 'r': right-aligned
% When not enough entries are specified, the specification is repeated
% cyclically.
%
% Output: table as a string
%
% See https://help.github.com/articles/github-flavored-markdown/#tables
% input argument validation and normalization
nCols = size(data, 2);
if ~exist('alignment','var') || isempty(alignment)
alignment = 'l';
end
if numel(alignment) < nCols
% repeat the alignment specifications along the columns
alignment = repmat(alignment, 1, nCols);
alignment = alignment(1:nCols);
end
% calculate the required column width
cellWidth = cellfun(@length, [header(:)' ;data]);
columnWidth = max(max(cellWidth, [], 1),3); % use at least 3 places
% prepare the table format
COLSEP = '|'; ROWSEP = sprintf('\n');
rowformat = [COLSEP sprintf([' %%%ds ' COLSEP], columnWidth) ROWSEP];
alignmentRow = formatAlignment(alignment, columnWidth);
% actually print the table
fullTable = [header; alignmentRow; data];
strs = cell(size(fullTable,1), 1);
for iRow = 1:numel(strs)
thisRow = fullTable(iRow,:);
%TODO: maybe preprocess thisRow with strjust first
strs{iRow} = sprintf(rowformat, thisRow{:});
end
str = [strs{:}];
%---------------------------------------------------------------------------
function alignRow = formatAlignment(alignment, columnWidth)
% Construct a row of dashes to specify the alignment of each column
% See https://help.github.com/articles/github-flavored-markdown/#tables
DASH = '-'; COLON = ':';
N = numel(columnWidth);
alignRow = arrayfun(@(w) repmat(DASH, 1, w), columnWidth, ...
'UniformOutput', false);
for iColumn = 1:N
thisAlign = alignment(iColumn);
thisSpec = alignRow{iColumn};
switch lower(thisAlign)
case 'l'
thisSpec(1) = COLON;
case 'r'
thisSpec(end) = COLON;
case 'c'
thisSpec([1 end]) = COLON;
otherwise
error('gfmTable:BadAlignment','Unknown alignment "%s"',...
thisAlign);
end
alignRow{iColumn} = thisSpec;
end
end
end
function str = gfmCode(str, inline, language)
% Construct a GFM code fragment
%
% Arguments:
% - str: code to be displayed
% - inline: - true -> formats inline
% - false -> formats as code block
% - [] -> automatic mode (default): picks one of the above
% - language: which language the code is (enforces a code block)
%
% Output: GFM formatted string
%
% See https://help.github.com/articles/github-flavored-markdown
if ~exist('inline','var')
inline = [];
end
if ~exist('language','var') || isempty(language)
language = '';
else
inline = false; % highlighting is not supported for inline code
end
if isempty(inline)
inline = isempty(strfind(str, sprintf('\n')));
end
if inline
prefix = '`';
postfix = '`';
else
prefix = sprintf('\n```%s\n', language);
postfix = sprintf('\n```\n');
if str(end) == sprintf('\n')
postfix = postfix(2:end); % remove extra endline
end
end
str = sprintf('%s%s%s', prefix, str, postfix);
end
function str = gfmHeader(str, level)
% Constructs a GFM/Markdown header
if ~exist('level','var')
level = 1;
end
str = sprintf('\n%s %s\n', repmat('#', 1, level), str);
end
function symbols = githubEmoji()
% defines the emojis to signal the test result
symbols = struct('pass', ':white_check_mark:', ...
'fail', ':heavy_exclamation_mark:', ...
'skip', ':grey_question:');
end
% ==============================================================================
function S = splitStatuses(status)
% splits a cell array of statuses into a struct of cell arrays
% of statuses according to their value of "skip", "reliable" and whether
% an error has occured.
% See also: splitUnreliableTests, splitPassFailSkippedTests
S = struct('all', {status}); % beware of cell array assignment to structs!
[S.reliable, S.unreliable] = splitUnreliableTests(status);
[S.passR, S.failR, S.skipR] = splitPassFailSkippedTests(S.reliable);
[S.passU, S.failU, S.skipU] = splitPassFailSkippedTests(S.unreliable);
end
% ==============================================================================
function [short, long] = describeEnvironment()
% describes the environment in a short and long format
[env, ver] = getEnvironment;
[dummy, VCID] = VersionControlIdentifier(); %#ok
if ~isempty(VCID)
VCID = [' commit ' VCID(1:10)];
end
OS = OSVersion;
short = sprintf('%s %s (%s)', env, ver, OS, VCID);
long = sprintf('Test results for m2t%s running with %s %s on %s.', ...
VCID, env, ver, OS);
end
% ==============================================================================
function reportUnreliableTests(stream, arg, S)
% report on the unreliable tests
if ~isempty(S.unreliable) && ~strcmpi(arg.length, 'short')
stream.print(gfmHeader('Unreliable tests',2));
stream.print('These do not cause the build to fail.\n\n');
displayTestResults(stream, S.unreliable);
end
end
function reportReliableTests(stream, arg, S)
% report on the reliable tests
switch arg.length
case 'long'
tests = S.reliable;
message = '';
case 'default'
tests = [S.failR; S.skipR];
message = 'Passing tests are not shown (only failed and skipped tests).\n\n';
case 'short'
return; % don't show this part
end
stream.print(gfmHeader('Reliable tests',2));
stream.print('Only the reliable tests determine the build outcome.\n');
stream.print(message);
displayTestResults(stream, tests);
end
% ==============================================================================
function displayTestResults(stream, status)
% display a table of specific test outcomes
headers = {'Testcase', 'Name', 'OK', 'Status'};
data = cell(numel(status), numel(headers));
symbols = githubEmoji;
for iTest = 1:numel(status)
data(iTest,:) = fillTestResultRow(status{iTest}, symbols);
end
str = gfmTable(data, headers, 'llcl');
stream.print('%s', str);
end
function row = fillTestResultRow(oneStatus, symbol)
% format the status of a single test for the summary table
testNumber = oneStatus.index;
testSuite = func2str(oneStatus.testsuite);
summary = '';
if oneStatus.skip
summary = 'SKIPPED';
passOrFail = symbol.skip;
else
stages = getStagesFromStatus(oneStatus);
for jStage = 1:numel(stages)
thisStage = oneStatus.(stages{jStage});
if ~thisStage.error
continue;
end
stageName = strrep(stages{jStage},'Stage','');
switch stageName
case 'plot'
summary = sprintf('%s plot failed', summary);
case 'tikz'
summary = sprintf('%s m2t failed', summary);
case 'hash'
summary = sprintf('new hash %32s != expected (%32s) %s', ...
thisStage.found, thisStage.expected, summary);
otherwise
summary = sprintf('%s %s FAILED', summary, thisStage);
end
end
if isempty(summary)
passOrFail = symbol.pass;
else
passOrFail = symbol.fail;
end
summary = strtrim(summary);
end
row = { gfmCode(sprintf('%s(%d)', testSuite, testNumber)), ...
gfmCode(oneStatus.function), ...
passOrFail, ...
summary};
end
% ==============================================================================
function displayTestSummary(stream, S)
% display a table of # of failed/passed/skipped tests vs (un)reliable
% compute number of cases per category
reliableSummary = cellfun(@numel, {S.passR, S.failR, S.skipR});
unreliableSummary = cellfun(@numel, {S.passU, S.failU, S.skipU});
% make summary table + calculate totals
summary = [unreliableSummary numel(S.unreliable);
reliableSummary numel(S.reliable);
reliableSummary+unreliableSummary numel(S.all)];
% put results into cell array with proper layout
summary = arrayfun(@(v) sprintf('%d',v), summary, 'UniformOutput', false);
table = repmat({''}, 3, 5);
header = {'','Pass','Fail','Skip','Total'};
table(:,1) = {'Unreliable','Reliable','Total'};
table(:,2:end) = summary;
% print table
[envShort, envDescription] = describeEnvironment(); %#ok
stream.print(gfmHeader('Test summary', 2));
stream.print('%s\n', envDescription);
stream.print('%s\n', gfmCode(generateCode(S),false,'matlab'));
stream.print(gfmTable(table, header, 'lrrrr'));
% print overall outcome
symbol = githubEmoji;
nErrors = numel(S.failR);
if nErrors == 0
stream.print('\nBuild passes. %s\n', symbol.pass);
else
stream.print('\nBuild fails with %d errors. %s\n', nErrors, symbol.fail);
end
end
function code = generateCode(S)
% generates some MATLAB code to easily replicate the results
code = sprintf('%s = %s;\n', ...
'suite', ['@' func2str(S.all{1}.testsuite)], ...
'alltests', testNumbers(S.all), ...
'reliable', testNumbers(S.reliable), ...
'unreliable', testNumbers(S.unreliable), ...
'failReliable', testNumbers(S.failR), ...
'passUnreliable', testNumbers(S.passU), ...
'skipped', testNumbers([S.skipR; S.skipU]));
% --------------------------------------------------------------------------
function str = testNumbers(status)
str = intelligentVector( cellfun(@(s) s.index, status) );
end
end
function str = intelligentVector(numbers)
% Produce a string that is an intelligent vector notation of its arguments
% e.g. when numbers = [ 1 2 3 4 6 7 8 9 ], it should return '[ 1:4 6:9 ]'
% The order in the vector is not retained!
if isempty(numbers)
str = '[]';
else
numbers = sort(numbers(:).');
delta = diff([numbers(1)-1 numbers]);
% place virtual bounds at the first element and beyond the last one
bounds = [1 find(delta~=1) numel(numbers)+1];
idx = 1:(numel(bounds)-1); % start index of each segment
start = numbers(bounds(idx ) );
stop = numbers(bounds(idx+1)-1);
parts = arrayfun(@formatRange, start, stop, 'UniformOutput', false);
str = sprintf('[%s]', strtrim(sprintf('%s ', parts{:})));
end
end
function str = formatRange(start, stop)
% format a range [start:stop] of integers in MATLAB syntax
if start==stop
str = sprintf('%d',start);
else
str = sprintf('%d:%d',start, stop);
end
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
compareTimings.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/compareTimings.m
| 8,282 |
utf_8
|
9e1a7fc2d1d21b259ffc79d50827c481
|
function compareTimings(statusBefore, statusAfter)
% COMPARETIMINGS compare timing of matlab2tikz test suite runs
%
% This function plots some analysis plots of the timings of different test
% cases. When the test suite is run repeatedly, the median statistics are
% reported as well as the individual runs.
%
% Usage:
% COMPARETIMINGS(statusBefore, statusAfter)
%
% Parameters:
% - statusBefore and statusAfter are expected to be
% N x R cell arrays, each cell contains a status of a test case
% where there are N test cases, repeated R times each.
%
% You can build such cells, e.g. with the following snippet.
%
% suite = @ACID
% N = numel(suite(0)); % number of test cases
% R = 10; % number of repetitions of each test case
%
% statusBefore = cell(N, R);
% for r = 1:R
% statusBefore(:, r) = testHeadless;
% end
%
% % now check out the after commit
%
% statusAfter = cell(N, R);
% for r = 1:R
% statusAfter(:, r) = testHeadless;
% end
%
% compareTimings(statusBefore, statusAfter)
%
% See also: testHeadless
%% Extract timing information
time_cf = extract(statusBefore, statusAfter, @(s) s.tikzStage.cleanfigure_time);
time_m2t = extract(statusBefore, statusAfter, @(s) s.tikzStage.m2t_time);
%% Construct plots
hax(1) = subplot(3,2,1);
histograms(time_cf, 'cleanfigure');
legend('show')
hax(2) = subplot(3,2,3);
histograms(time_m2t, 'matlab2tikz');
legend('show')
linkaxes(hax([1 2]),'x');
hax(3) = subplot(3,2,5);
histogramSpeedup('cleanfigure', time_cf, 'matlab2tikz', time_m2t);
legend('show');
hax(4) = subplot(3,2,2);
plotByTestCase(time_cf, 'cleanfigure');
legend('show')
hax(5) = subplot(3,2,4);
plotByTestCase(time_m2t, 'matlab2tikz');
legend('show')
hax(6) = subplot(3,2,6);
plotSpeedup('cleanfigure', time_cf, 'matlab2tikz', time_m2t);
legend('show');
linkaxes(hax([4 5 6]), 'x');
% ------------------------------------------------------------------------------
end
%% Data processing
function timing = extract(statusBefore, statusAfter, func)
otherwiseNaN = {'ErrorHandler', @(varargin) NaN};
timing.before = cellfun(func, statusBefore, otherwiseNaN{:});
timing.after = cellfun(func, statusAfter, otherwiseNaN{:});
end
function [names,timings] = splitNameTiming(vararginAsCell)
names = vararginAsCell(1:2:end-1);
timings = vararginAsCell(2:2:end);
end
%% Plot subfunctions
function [h] = histograms(timing, name)
% plot histogram of time measurements
colors = colorscheme;
histostyle = {'DisplayStyle', 'bar',...
'Normalization','pdf',...
'EdgeColor','none',...
'BinWidth',0.025};
hold on;
h{1} = myHistogram(timing.before, histostyle{:}, ...
'FaceColor', colors.before, ...
'DisplayName', 'Before');
h{2} = myHistogram(timing.after , histostyle{:}, ...
'FaceColor', colors.after,...
'DisplayName', 'After');
xlabel(sprintf('%s runtime [s]',name))
ylabel('Empirical PDF');
end
function [h] = histogramSpeedup(varargin)
% plot histogram of observed speedup
histostyle = {'DisplayStyle', 'bar',...
'Normalization','pdf',...
'EdgeColor','none'};
[names,timings] = splitNameTiming(varargin);
nData = numel(timings);
h = cell(nData, 1);
minTime = NaN; maxTime = NaN;
for iData = 1:nData
name = names{iData};
timing = timings{iData};
hold on;
speedup = computeSpeedup(timing);
color = colorOptionsOfName(name, 'FaceColor');
h{iData} = myHistogram(speedup, histostyle{:}, color{:},...
'DisplayName', name);
[minTime, maxTime] = minAndMax(speedup, minTime, maxTime);
end
xlabel('Speedup')
ylabel('Empirical PDF');
set(gca,'XScale','log', 'XLim', [minTime, maxTime].*[0.9 1.1]);
end
function [h] = plotByTestCase(timing, name)
% plot all time measurements per test case
colors = colorscheme;
hold on;
if size(timing.before, 2) > 1
h{3} = plot(timing.before, '.',...
'Color', colors.before, 'HandleVisibility', 'off');
h{4} = plot(timing.after, '.',...
'Color', colors.after, 'HandleVisibility', 'off');
end
h{1} = plot(median(timing.before, 2), '-',...
'LineWidth', 2, ...
'Color', colors.before, ...
'DisplayName', 'Before');
h{2} = plot(median(timing.after, 2), '-',...
'LineWidth', 2, ...
'Color', colors.after,...
'DisplayName', 'After');
ylabel(sprintf('%s runtime [s]', name));
set(gca,'YScale','log')
end
function [h] = plotSpeedup(varargin)
% plot speed up per test case
[names, timings] = splitNameTiming(varargin);
nDatasets = numel(names);
minTime = NaN;
maxTime = NaN;
h = cell(nDatasets, 1);
for iData = 1:nDatasets
name = names{iData};
timing = timings{iData};
color = colorOptionsOfName(name);
hold on
[speedup, medSpeedup] = computeSpeedup(timing);
if size(speedup, 2) > 1
plot(speedup, '.', color{:}, 'HandleVisibility','off');
end
h{iData} = plot(medSpeedup, color{:}, 'DisplayName', name, ...
'LineWidth', 2);
[minTime, maxTime] = minAndMax(speedup, minTime, maxTime);
end
nTests = size(speedup, 1);
plot([-nTests nTests*2], ones(2,1), 'k','HandleVisibility','off');
legend('show', 'Location','NorthWest')
set(gca,'YScale','log','YLim', [minTime, maxTime].*[0.9 1.1], ...
'XLim', [0 nTests+1])
xlabel('Test case');
ylabel('Speed-up (t_{before}/t_{after})');
end
%% Histogram wrapper
function [h] = myHistogram(data, varargin)
% this is a very crude wrapper that mimics Histogram in R2014a and older
if ~isempty(which('histogram'))
h = histogram(data, varargin{:});
else % no "histogram" available
options = struct(varargin{:});
minData = min(data(:));
maxData = max(data(:));
if isfield(options, 'BinWidth')
numBins = ceil((maxData-minData)/options.BinWidth);
elseif isfield(options, 'NumBins')
numBins = options.NumBins;
else
numBins = 10;
end
[counts, bins] = hist(data(:), numBins);
if isfield(options,'Normalization') && strcmp(options.Normalization,'pdf')
binWidth = mean(diff(bins));
counts = counts./sum(counts)/binWidth;
end
h = bar(bins, counts, 1);
% transfer properties as well
names = fieldnames(options);
for iName = 1:numel(names)
option = names{iName};
if isprop(h, option)
set(h, option, options.(option));
end
end
set(allchild(h),'FaceAlpha', 0.75); % only supported with OpenGL renderer
% but this should look a bit similar with matlab2tikz then...
end
end
%% Calculations
function [speedup, medSpeedup] = computeSpeedup(timing)
% computes the timing speedup (and median speedup)
dRep = 2; % dimension containing the repeated tests
speedup = timing.before ./ timing.after;
medSpeedup = median(timing.before, dRep) ./ median(timing.after, dRep);
end
function [minTime, maxTime] = minAndMax(speedup, minTime, maxTime)
% calculates the minimum/maximum time in an array and peviously
% computed min/max times
minTime = min([minTime; speedup(:)]);
maxTime = min([maxTime; speedup(:)]);
end
%% Color scheme
function colors = colorscheme()
% defines the color scheme
colors.matlab2tikz = [161 19 46]/255;
colors.cleanfigure = [ 0 113 188]/255;
colors.before = [236 176 31]/255;
colors.after = [118 171 47]/255;
end
function color = colorOptionsOfName(name, keyword)
% returns a cell array with a keyword (default: 'Color') and a named color
% if it exists in the colorscheme
if ~exist('keyword','var') || isempty(keyword)
keyword = 'Color';
end
colors = colorscheme;
if isfield(colors,name)
color = {keyword, colors.(name)};
else
color = {};
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
issues.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/suites/issues.m
| 1,221 |
utf_8
|
fe24b770a80dd53470798dfce281989a
|
function [ status ] = issues( k )
%ISSUES M2T Test cases related to issues
%
% Issue-related test cases for matlab2tikz
%
% See also: ACID, matlab2tikz_acidtest
testfunction_handles = {
@scatter3Plot3
};
numFunctions = length( testfunction_handles );
if (k<=0)
status = testfunction_handles;
return; % This is used for querying numFunctions.
elseif (k<=numFunctions)
status = testfunction_handles{k}();
status.function = func2str(testfunction_handles{k});
else
error('issues:outOfBounds', ...
'Out of bounds (number of testfunctions=%d)', numFunctions);
end
end
% =========================================================================
function [stat] = scatter3Plot3()
stat.description = 'Scatter3 plot with 2 colors';
stat.issues = 292;
hold on;
x = sin(1:5);
y = cos(3.4 *(1:5));
z = x.*y;
scatter3(x,y,z,150,...
'MarkerEdgeColor','none','MarkerFaceColor','k');
scatter3(-x,y,z,150,...
'MarkerEdgeColor','none','MarkerFaceColor','b');
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
ACID.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/suites/ACID.m
| 97,752 |
utf_8
|
215aa8933946f46d2472aea446eb2dd4
|
% =========================================================================
% *** FUNCTION ACID
% ***
% *** MATLAB2TikZ ACID test functions
% ***
% =========================================================================
function [status] = ACID(k)
% assign the functions to test
testfunction_handles = { ...
@multiline_labels , ...
@plain_cos , ...
@sine_with_markers , ...
@markerSizes , ...
@markerSizes2 , ...
@sine_with_annotation, ...
@linesWithOutliers , ...
@peaks_contour , ...
@contourPenny , ...
@peaks_contourf , ...
@many_random_points , ...
@double_colorbar , ...
@randomWithLines , ...
@double_axes , ...
@double_axes2 , ...
@logplot , ...
@colorbarLogplot , ...
@legendplot , ...
@legendplotBoxoff , ...
@plotyyLegends , ...
@zoom , ...
@quiveroverlap , ...
@quiverplot , ...
@quiver3plot , ...
@logicalImage , ...
@imagescplot , ...
@imagescplot2 , ...
@stairsplot , ...
@polarplot , ...
@roseplot , ...
@compassplot , ...
@stemplot , ...
@stemplot2 , ...
@bars , ...
@xAxisReversed , ...
@errorBars , ...
@errorBars2 , ...
@subplot2x2b , ...
@manualAlignment , ...
@subplotCustom , ...
@legendsubplots , ...
@bodeplots , ...
@rlocusPlot , ...
@mandrillImage , ...
@besselImage , ...
@clownImage , ...
@zplanePlot1 , ...
@zplanePlot2 , ...
@freqResponsePlot , ...
@axesLocation , ...
@axesColors , ...
@multipleAxes , ...
@scatterPlotRandom , ...
@scatterPlot , ...
@scatter3Plot , ...
@spherePlot , ...
@surfPlot , ...
@surfPlot2 , ...
@superkohle , ...
@meshPlot , ...
@ylabels , ...
@spectro , ... % takes pretty long to LuaLaTeX-compile
@mixedBarLine , ...
@decayingharmonic , ...
@texcolor , ...
@textext , ...
@texrandom , ...
@latexInterpreter , ...
@latexmath2 , ...
@parameterCurve3d , ...
@parameterSurf , ...
@fill3plot , ...
@rectanglePlot , ...
@herrorbarPlot , ...
@hist3d , ...
@myBoxplot , ...
@areaPlot , ...
@customLegend , ...
@pixelLegend , ...
@croppedImage , ...
@pColorPlot , ...
@hgTransformPlot , ...
@scatterPlotMarkers , ...
@multiplePatches , ...
@logbaseline , ...
@alphaImage , ...
@annotationAll , ...
@annotationSubplots , ...
@annotationText , ...
@annotationTextUnits , ...
@imageOrientation_PNG, ...
@imageOrientation_inline, ...
@texInterpreter , ...
@stackedBarsWithOther, ...
@colorbarLabelTitle , ...
@textAlignment , ...
@overlappingPlots , ...
@histogramPlot , ...
@alphaTest , ...
@removeOutsideMarker , ...
@colorbars , ...
@colorbarManualLocationRightOut , ...
@colorbarManualLocationRightIn , ...
@colorbarManualLocationLeftOut , ...
@colorbarManualLocationLeftIn
};
numFunctions = length( testfunction_handles );
if (k<=0)
status = testfunction_handles;
return; % This is used for querying numFunctions.
elseif (k<=numFunctions)
status = testfunction_handles{k}();
status.function = func2str(testfunction_handles{k});
else
error('testfunctions:outOfBounds', ...
'Out of bounds (number of testfunctions=%d)', numFunctions);
end
end
% =========================================================================
function data = ACID_data()
% Data to be used for various ACID tests
% This ensures the tests don't rely on functions that yield
% non-deterministic output, e.g. `rand` and `svd`.
data = [ 11 11 9
7 13 11
14 17 20
11 13 9
43 51 69
38 46 76
61 132 186
75 135 180
38 88 115
28 36 55
12 12 14
18 27 30
18 19 29
17 15 18
19 36 48
32 47 10
42 65 92
57 66 151
44 55 90
114 145 257
35 58 68
11 12 15
13 9 15
10 9 7];
end
% =========================================================================
function [stat] = multiline_labels()
stat.description = 'Test multiline labels and plot some points.';
stat.unreliable = isOctave || isMATLAB(); %FIXME: `width` is inconsistent, see #552
m = [0 1 1.5 1 -1];
plot(m,'*-'); hold on;
plot(m(end:-1:1)-0.5,'x--');
title({'multline','title'});
legend({sprintf('multi-line legends\ndo work 2^2=4'), ...
sprintf('second\nplot')});
xlabel(sprintf('one\ntwo\nthree'));
ylabel({'one','° ∞', 'three'});
set(gca,'YTick', []);
set(gca,'XTickLabel',{});
end
% =========================================================================
function [stat] = plain_cos()
stat.description = 'Plain cosine function.';
t = linspace(0, 2*pi, 1e5);
x = cos(t);
% Explicitely cut the line into segments
x([2e4, 5e4, 8e4]) = NaN;
% Plot the cosine
plot(t, x);
xlim([0, 2*pi]);
% also add some patches to test their border color reproduction
hold on;
h(1) = fill(pi*[1/4 1/4 1/2 1/2] , [-2 1 1 -2], 'y');
h(2) = fill(pi*[1/4 1/4 1/2 1/2]+pi, -[-2 1 1 -2], 'y');
set(h(1), 'EdgeColor', 'none', 'FaceColor', 0.8*[1 1 1]);
set(h(2), 'EdgeColor', 'k', 'FaceColor', 0.5*[1 1 1]);
if isMATLAB
uistack(h, 'bottom'); % patches below the line plot
% this is not supported in Octave
end
% add some minor ticks
set(gca, 'XMinorTick', 'on');
set(gca, 'YTick', []);
% Adjust the aspect ratio when in MATLAB(R) or Octave >= 3.4.
if isOctave('<=', [3,4])
% Octave < 3.4 doesn't have daspect unfortunately.
else
daspect([ 1 2 1 ])
end
end
% =========================================================================
function [stat] = sine_with_markers ()
% Standard example plot from MATLAB's help pages.
stat.description = [ 'Twisted plot of the sine function. ' ,...
'Pay particular attention to how markers and Infs/NaNs are treated.' ];
x = -pi:pi/10:pi;
y = sin(x);
y(3) = NaN;
y(7) = Inf;
y(11) = -Inf;
plot(x,y,'--o', 'Color', [0.6,0.2,0.0], ...
'LineWidth', 1*360/127,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[0.3,0.1,0.0],...
'MarkerSize', 5*360/127 );
set( gca, 'Color', [0.9 0.9 1], ...
'XTickLabel', [], ...
'YTickLabel', [] ...
);
set(gca,'XTick',[0]);
set(gca,'XTickLabel',{'null'});
end
% =========================================================================
function [stat] = markerSizes()
stat.description = 'Marker sizes.';
hold on;
h = fill([1 1 2 2],[1 2 2 1],'r');
set(h,'LineWidth',10);
plot([0],[0],'go','Markersize',14,'LineWidth',10)
plot([0],[0],'bo','Markersize',14,'LineWidth',1)
end
% =========================================================================
function [stat] = markerSizes2()
stat.description = 'Line plot with with different marker sizes.';
hold on;
grid on;
n = 1:10;
d = 10;
s = round(linspace(6,25,10));
e = d * ones(size(n));
style = {'bx','rd','go','c.','m+','y*','bs','mv','k^','r<','g>','cp','bh'};
nStyles = numel(style);
for ii = 1:nStyles
for jj = 1:10
plot(n(jj), ii * e(jj),style{ii},'MarkerSize',s(jj));
end
end
xlim([min(n)-1 max(n)+1]);
ylim([0 d*(nStyles+1)]);
set(gca,'XTick',n,'XTickLabel',s,'XTickLabelMode','manual');
end
% =========================================================================
function [stat] = sine_with_annotation ()
stat.description = [ 'Plot of the sine function. ',...
'Pay particular attention to how titles and annotations are treated.' ];
stat.unreliable = isOctave || isMATLAB('>=',[8,4]) ... %FIXME: investigate
|| isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
x = -pi:.1:pi; %TODO: the 0.1 step is probably a bad idea (not representable in float)
y = sin(x);
h = plot(x,y);
set(gca,'XTick',-pi:pi/2:pi);
set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'});
xlabel('-\pi \leq \Theta \leq \pi');
ylabel('sin(\Theta)');
title({'Plot of sin(\Theta)','subtitle','and here''s one really long subtitle' });
text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',...
'HorizontalAlignment','left');
% Doesn't work in Octave
%set(findobj(gca,'Type','line','Color',[0 0 1]),...
% 'Color','red',...
% 'LineWidth',10);
end
% =========================================================================
function [stat] = linesWithOutliers()
stat.description = 'Lines with outliers.';
stat.issues = [392,400];
far = 200;
x = [ -far, -1, -1, -far, -10, -0.5, 0.5, 10, far, 1, 1, far, 10, 0.5, -0.5, -10, -far ];
y = [ -10, -0.5, 0.5, 10, far, 1, 1, far, 10, 0.5, -0.5, -10, -far, -1, -1, -far, -0.5 ];
plot( x, y,'o-');
axis( [-2,2,-2,2] );
end
% =========================================================================
function [stat] = peaks_contour()
stat.description = 'Test contour plots.';
stat.unreliable = isMATLAB('<', [8,4]) || isOctave; %R2014a and older
% FIXME: see #604; contour() produces inconsistent output
subplot(121)
[C, h] = contour(peaks(20),10);
clabel(C, h);
% remove y-ticks
set(gca,'YTickLabel',[]);
set(gca,'YTick',[]);
colormap winter;
% Contour layers with predefined color
subplot(122)
contour(peaks(20), 10,'r', 'LineWidth', 5)
set(gca,'YTickLabel',[]);
set(gca,'YTick',[]);
end
% =========================================================================
function [stat] = contourPenny()
stat.description = 'Contour plot of a US\$ Penny.';
stat.unreliable = isMATLAB('<', [8,4]);
% FIXME: see #604; contour() produces inconsistent output (mac/windows of PeterPablo)
stat.issues = [49 404];
if ~exist('penny.mat','file')
fprintf( 'penny data set not found. Skipping.\n\n' );
stat.skip = true;
return;
end
load penny;
contour(flipud(P));
axis square;
end
% =========================================================================
function [stat] = peaks_contourf ()
stat.description = 'Test the contourfill plots.';
stat.unreliable = isMATLAB('>=', [8,4]); % FIXME: inspect this
stat.issues = 582;
[trash, h] = contourf(peaks(20), 10);
hold on
plot(1:20)
colorbar();
legend(h, 'Contour');
colormap hsv;
end
% =========================================================================
function [stat] = double_colorbar()
stat.description = 'Double colorbar.';
if isOctave()
fprintf( 'Octave can''t handle tight axes.\n\n' );
stat.skip = true;
return
end
vspace = linspace(-40,40,20);
speed_map = magic(20).';
Q1_map = magic(20);
subplot(1, 2, 1);
contour(vspace(9:17),vspace(9:17),speed_map(9:17,9:17),20)
colorbar
axis tight
axis square
xlabel('$v_{2d}$')
ylabel('$v_{2q}$')
subplot(1, 2, 2)
contour(vspace(9:17),vspace(9:17),Q1_map(9:17,9:17),20)
colorbar
axis tight
axis square
xlabel('$v_{2d}$')
ylabel('$v_{2q}$')
end
% =========================================================================
function [stat] = randomWithLines()
stat.description = 'Lissajous points with lines.';
beta = 42.42;
t = 1:150;
X = [sin(t); cos(beta * t)].';
X(:,1) = (X(:,1) * 90) + 75;
plot(X(:,1),X(:,2),'o');
hold on;
M(1)=min(X(:,1));
M(2)=max(X(:,1));
mn = mean(X(:,2));
s = std(X(:,2));
plot(M,[mean(X(:,2)) mean(X(:,2))],'k-');
plot(M,mn + 1*[s s],'--');
plot(M,mn - 2*[s s],'--');
axis('tight');
end
% =========================================================================
function [stat] = many_random_points ()
stat.description = 'Test the performance when drawing many points.';
n = 1e3;
alpha = 1024;
beta = 1;
gamma = 5.47;
x = cos( (1:n) * alpha );
y = sin( (1:n) * beta + gamma);
plot ( x, y, '.r' );
axis([ 0, 1, 0, 1 ])
end
% =========================================================================
function [stat] = double_axes()
stat.description = 'Double axes';
dyb = 0.1; % normalized units, bottom offset
dyt = 0.1; % separation between subsequent axes bottoms
x = [0; 24; 48; 72; 96;];
y = [7.653 7.473 7.637 7.652 7.651];
grid on
h1 = plot(x,y,'Color','k');
% following code is taken from `floatAxisX.m'
% get position of axes
allAxes = findobj(gcf,'type','axes');
naxes = length(allAxes);
ax1Pos = get(allAxes(naxes),'position');
% rescale and reposition all axes to handle additional axes
for an=1:naxes-1
if isequal(rem(an,2),0)
% even ones in array of axes handles represent axes on which lines are plotted
set(allAxes(an),'Position',[ax1Pos(1,1) ax1Pos(1,2)+dyb ax1Pos(1,3) ax1Pos(1,4)-dyt])
else
% odd ones in array of axes handles represent axes on which floating x-axss exist
axPos = get(allAxes(an),'Position');
set(allAxes(an),'Position',[axPos(1,1) axPos(1,2)+dyb axPos(1,3) axPos(1,4)])
end
end
% first axis a special case (doesn't fall into even/odd scenario of figure children)
set(allAxes(naxes),'Position',[ax1Pos(1,1) ax1Pos(1,2)+dyb ax1Pos(1,3) ax1Pos(1,4)-dyt])
ylimit1 = get(allAxes(naxes),'Ylim');
% get new position for plotting area of figure
ax1Pos = get(allAxes(naxes),'position');
% axis to which the floating axes will be referenced
ref_axis = allAxes(1);
refPosition = get(ref_axis,'position');
% overlay new axes on the existing one
ax2 = axes('Position',ax1Pos);
% plot data and return handle for the line
hl1 = plot(x,y,'k');
% make the new axes invisible, leaving only the line visible
set(ax2,'visible','off','ylim',ylimit1)
% set the axis limit mode so that it does not change if the
% user resizes the figure window
set(ax2,'xLimMode','manual')
% set up another set of axes to act as floater
ax3 = axes('Position',[refPosition(1) refPosition(2)-dyb refPosition(3) 0.01]);
set(ax3,'box','off','ycolor','w','yticklabel',[],'ytick',[])
set(ax3,'XMinorTick','on','color','none','xcolor',get(hl1,'color'))
xlabel('secondary axis')
end
% =========================================================================
function [stat] = double_axes2()
stat.description = 'Double overlayed axes with a flip.' ;
ah1=axes;
ph=plot([0 1],[0 1]);
title('Title')
ylabel('y')
xlabel('x')
% add a new set of axes
% to make a gray grid
ah2=axes;
% make the background transparent
set(ah1,'color','none')
% move these axes to the back
set(gcf,'Children',flipud(get(gcf,'Children')))
end
% =========================================================================
function [stat] = logplot()
stat.description = 'Test logscaled axes.';
% This was once unreliable (and linked to #590). Mac and Linux seem fine.
x = logspace(-1,2);
y = exp(x);
loglog(x, y, '-s')
ylim([1 1e45]);
grid on;
if isprop(gca,'GridColor')
set(gca, 'GridColor', 'red');
set(gca, 'MinorGridColor', 'blue');
else
%TODO equivalent HG1 settings (if those exist)
end
end
% =========================================================================
function [stat] = colorbarLogplot()
stat.description = 'Logscaled colorbar.';
stat.unreliable = isOctave; % FIXME: investigate (Travis differs from Linux/Mac octave)
% https://github.com/matlab2tikz/matlab2tikz/pull/641#issuecomment-120481564
imagesc([1 10 100]);
try
set(colorbar(), 'YScale', 'log');
catch
warning('M2TAcid:LogColorBar',...
'Logarithmic Colorbars are not documented in MATLAB R2014b and Octave');
stat.skip = true;
end
end
% =========================================================================
function [stat] = legendplot()
stat.description = 'Test inserting of legends.';
stat.unreliable = isMATLAB || isOctave; % FIXME: investigate
% x = -pi:pi/20:pi;
% plot(x,cos(x),'-ro',x,sin(x),'-.b');
% h = legend('one pretty long legend cos_x','sin_x',2);
% set(h,'Interpreter','none');
x = linspace(0, 2*pi, 1e5);
plot( x, sin(x), 'b', ...
x, cos(x), 'r' );
xlim( [0 2*pi] )
ylim( [-0.9 0.9] )
title( '{tikz test}' )
xlabel( '{x-Values}' )
ylabel( '{y-Values}' )
legend( 'sin(x)', 'cos(x)', 'Location','NorthOutside', ...
'Orientation', 'Horizontal' );
grid on;
end
% =========================================================================
function [stat] = legendplotBoxoff ()
stat.description = 'Test inserting of legends.';
stat.issues = [607,609];
x = -pi:pi/20:pi;
l = plot(x, cos(x),'-ro',...
x, sin(x),'-.b');
h = legend(l(2), 'one pretty long legend sin_x (dash-dot)', 'Location', 'northeast');
set(h, 'Interpreter', 'none');
legend boxoff
end
% =========================================================================
function [stat] = plotyyLegends()
stat.description = 'More legends.';
x = 0:.1:7;
y1 = sin(x);
y2 = cos(x);
[ax,h1,h2] = plotyy(x,y1,x,y2);
legend([h1;h2],'Sine','Cosine');
end
% =========================================================================
function [stat] = zoom()
stat.description = ['Test function \texttt{pruneOutsideBox()} ', ...
'and \texttt{movePointsCloser()} ', ...
'of \texttt{cleanfigure()}.'];
stat.unreliable = isOctave; %FIXME: investigate
stat.issues = [226,392,400];
% Setup
subplot(311)
plot(1:10,10:-1:1,'-r*',1:15,repmat(9,1,15),'-g*',[5.5,5.5],[1,9],'-b*')
hold on;
stairs(1:10,'-m*');
plot([2,8.5,8.5,2,2],[2,2,7.5,7.5,2],'--k');
title('setup');
legend('cross with points','no cross','cross no points','stairs','zoom area');
% Last comes before simple zoomin due to cleanfigure
subplot(313)
plot(1:10,10:-1:1,'-r*',1:10,repmat(9,1,10),'-g*',[5.5,5.5],[1,9],'-b*');
hold on;
stairs(1:10,'-m*');
xlim([2, 8.5]), ylim([2,7.5]);
cleanfigure(); % FIXME: this generates many "division by zero" in Octave
plot([2,8.5,8.5,2,2],[2,2,7.5,7.5,2],'--k');
xlim([0, 15]), ylim([0,10]);
title('zoom in, cleanfigure, zoom out');
% Simple zoom in
subplot(312)
plot(1:10,10:-1:1,'-r*',1:10,repmat(9,1,10),'-g*',[5.5,5.5],[1,9],'-b*');
hold on;
stairs(1:10,'-m*');
xlim([2, 8.5]), ylim([2,7.5]);
title('zoom in');
end
% =========================================================================
function [stat] = bars()
stat.description = '2x2 Subplot with different bars';
stat.unreliable = isOctave || isMATLAB('>=', [8,4]) || ... % FIXME: investigate
isMATLAB('<=', [8,3]); %FIXME: #749 (Jenkins)
% dataset grouped
bins = 10 * (-0.5:0.1:0.5);
numEntries = length(bins);
alpha = [13 11 7];
numBars = numel(alpha);
plotData = zeros(numEntries, numBars);
for iBar = 1:numBars
plotData(:,iBar) = abs(round(100*sin(alpha(iBar)*(1:numEntries))));
end
% dataset stacked
data = ACID_data;
Y = round(abs(data(2:6,1:3))/10);
subplot(2,2,1);
b1 = bar(bins,plotData,'grouped','BarWidth',1.5);
set(gca,'XLim',[1.25*min(bins) 1.25*max(bins)]);
subplot(2,2,2);
barh(bins, plotData, 'grouped', 'BarWidth', 1.3);
subplot(2,2,3);
bar(Y, 'stacked');
subplot(2,2,4);
b2= barh(Y,'stacked','BarWidth', 0.75);
set(b1(1),'FaceColor','m','EdgeColor','none')
set(b2(1),'FaceColor','c','EdgeColor','none')
end
% =========================================================================
function [stat] = stemplot()
stat.description = 'A simple stem plot.' ;
x = 0:25;
y = [exp(-.07*x).*cos(x);
exp(.05*x).*cos(x)]';
h = stem(x, y);
legend( 'exp(-.07x)*cos(x)', 'exp(.05*x)*cos(x)', 'Location', 'NorthWest');
set(h(1),'MarkerFaceColor','blue');
set(h(2),'MarkerFaceColor','red','Marker','square');
% Octave 4 has some smart behavior: it only prints a single baseline.
% Let's mimick this behavior everywhere else.
baselines = findall(gca, 'Type', 'line', 'Color', [0 0 0]);
if numel(baselines) > 1
% We only need the last line in Octave 3.8, as that is where
% Octave 4.0 places the baseline
delete(baselines(1:end-1));
end
end
% =========================================================================
function [stat] = stemplot2()
stat.description = 'Another simple stem plot.';
stat.unreliable = isOctave('>=', 4); %FIXME: see #759, #757/#759 and #687
x = 0:25;
y = [exp(-.07*x).*cos(x);
exp(.05*x).*cos(x)]';
h = stem(x, y, 'filled');
legend( 'exp(-.07x)*cos(x)', 'exp(.05*x)*cos(x)', 'Location', 'NorthWest');
end
% =========================================================================
function [stat] = stairsplot()
stat.description = 'A simple stairs plot.' ;
X = linspace(-2*pi,2*pi,40)';
Yconst = [zeros(10,1); 0.5*ones(20,1);-0.5*ones(10,1)];
Y = [sin(X), 0.2*cos(X), Yconst];
h = stairs(Y);
legend(h(2),'second entry')
end
% =========================================================================
function [stat] = quiverplot()
stat.description = 'A combined quiver/contour plot of $x\exp(-x^2-y^2)$.' ;
stat.extraOptions = {'arrowHeadSize', 2};
[X,Y] = meshgrid(-2:.2:2);
Z = X.*exp(-X.^2 - Y.^2);
[DX,DY] = gradient(Z,.2,.2);
contour(X,Y,Z);
hold on
quiver(X,Y,DX,DY);
%TODO: also show a `quiver(X,Y,DX,DY,0);` to test without scaling
colormap hsv;
hold off
end
% =========================================================================
function [stat] = quiver3plot()
stat.description = 'Three-dimensional quiver plot.' ;
stat.unreliable = isMATLAB(); %FIXME: #590
vz = 10; % Velocity
a = -32; % Acceleration
t = 0:.1:1;
z = vz*t + 1/2*a*t.^2;
vx = 2;
x = vx*t;
vy = 3;
y = vy*t;
u = gradient(x);
v = gradient(y);
w = gradient(z);
scale = 0;
quiver3(x,y,z,u,v,w,scale)
view([70 18])
end
% =========================================================================
function [stat] = quiveroverlap ()
stat.description = 'Quiver plot with avoided overlap.';
stat.issues = [679];
% TODO: As indicated in #679, the native quiver scaling algorithm still isn't
% perfect. As such, in MATLAB the arrow heads may appear extremely tiny.
% In Octave, they look fine though. Once the scaling has been done decently,
% this reminder can be removed.
if isOctave
stat.extraOptions = {'arrowHeadSize', 20};
end
x = [0 1];
y = [0 0];
u = [1 -1];
v = [1 1];
hold all;
qvr1 = quiver(x,y,u,v);
qvr2 = quiver(x,y,2*u,2*v);
set(qvr2, 'MaxHeadSize', get(qvr1, 'MaxHeadSize')/2);
end
% =========================================================================
function [stat] = polarplot ()
stat.description = 'A simple polar plot.' ;
stat.extraOptions = {'showHiddenStrings',true};
stat.unreliable = isOctave('>=', 4) || ... %FIXME: see #759, #757/#759 and #687
isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
t = 0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t),'--r')
end
% =========================================================================
function [stat] = roseplot ()
stat.description = 'A simple rose plot.' ;
stat.extraOptions = {'showHiddenStrings',true};
stat.unreliable = isOctave('>=', 4) || ... %FIXME: see #759, #757/#759 and #687
isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
theta = 2*pi*sin(linspace(0,8,100));
rose(theta);
end
% =========================================================================
function [stat] = compassplot ()
stat.description = 'A simple compass plot.' ;
stat.extraOptions = {'showHiddenStrings',true};
stat.unreliable = isOctave('>=', 4) || ... %FIXME: see #759, #757/#759 and #687
isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
Z = (1:20).*exp(1i*2*pi*cos(1:20));
compass(Z);
end
% =========================================================================
function [stat] = logicalImage()
stat.description = 'An image plot of logical matrix values.' ;
stat.unreliable = isOctave; %FIXME: investigate
% different `width`, see issue #552# (comment 76918634); (Travis differs from Linux/Mac octave)
plotData = magic(10);
imagesc(plotData > mean(plotData(:)));
colormap('hot');
end
% =========================================================================
function [stat] = imagescplot()
stat.description = 'An imagesc plot of $\sin(x)\cos(y)$.';
stat.unreliable = isOctave; %FIXME: investigate (Travis differs from Linux/Mac octave)
pointsX = 10;
pointsY = 20;
x = 0:1/pointsX:1;
y = 0:1/pointsY:1;
z = sin(x)'*cos(y);
imagesc(x,y,z);
end
% =========================================================================
function [stat] = imagescplot2()
stat.description = 'A trimmed imagesc plot.';
stat.unreliable = isOctave; %FIXME: investigate (Travis differs from Linux/Mac octave)
a=magic(10);
x=-5:1:4;
y=10:19;
imagesc(x,y,a)
xlim([-3,2])
ylim([12,15])
grid on;
end
% =========================================================================
function [stat] = xAxisReversed ()
stat.description = 'Reversed axes with legend.' ;
n = 100;
x = (0:1/n:1);
y = exp(x);
plot(x,y);
set(gca,'XDir','reverse');
set(gca,'YDir','reverse');
if isOctave('<=', [3,8])
% TODO: see whether we can unify this syntax for all environments
% at the moment, the generic syntax doesn't seem to work for Octave
% 3.8 (it doesn't even show a legend in gnuplut).
legend( 'data1', 'Location', 'SouthWest' );
else
legend( 'Location', 'SouthWest' );
end
end
% =========================================================================
function [stat] = subplot2x2b ()
stat.description = 'Three aligned subplots on a $2\times 2$ subplot grid.' ;
stat.unreliable = isOctave || isMATLAB();
% FIXME: this test is unreliable because the automatic axis limits
% differ on different test platforms. Reckon this by creating the figure
% using `ACID(97)` and then manually slightly modify the window size.
% We should not set the axis limits explicitly rather find a better way.
% #591
x = (1:5);
subplot(2,2,1);
y = sin(x.^3);
plot(x,y);
subplot(2,2,2);
y = cos(x.^3);
plot(x,y);
subplot(2,2,3:4);
y = tan(x);
plot(x,y);
end
% =========================================================================
function [stat] = manualAlignment()
stat.description = 'Manually aligned figures.';
xrange = linspace(-3,4,2*1024);
axes('Position', [0.1 0.1 0.85 0.15]);
plot(xrange);
ylabel('$n$');
xlabel('$x$');
axes('Position', [0.1 0.25 0.85 0.6]);
plot(xrange);
set(gca,'XTick',[]);
end
% =========================================================================
function [stat] = subplotCustom ()
stat.description = 'Three customized aligned subplots.';
stat.unreliable = isMATLAB(); % FIXME: #590
x = (1:5);
y = cos(sqrt(x));
subplot( 'Position', [0.05 0.1 0.3 0.3] )
plot(x,y);
y = sin(sqrt(x));
subplot( 'Position', [0.35 0.5 0.3 0.3] )
plot(x,y);
y = tan(sqrt(x));
subplot( 'Position', [0.65 0.1 0.3 0.3] )
plot(x,y);
end
% =========================================================================
function [stat] = errorBars()
stat.description = 'Generic error bar plot.';
data = ACID_data;
plotData = 1:10;
eH = abs(data(1:10,1))/10;
eL = abs(data(1:10,3))/50;
x = 1:10;
hold all;
errorbar(x, plotData, eL, eH, '.')
h = errorbar(x+0.5, plotData, eL, eH);
set(h, 'LineStyle', 'none');
% Octave 3.8 doesn't support passing extra options to |errorbar|, but
% it does allow for changing it after the fact
end
% =========================================================================
function [stat] = errorBars2()
stat.description = 'Another error bar example.';
data = ACID_data;
y = mean( data, 2 );
e = std( data, 1, 2 );
errorbar( y, e, 'xr' );
end
% =========================================================================
function [stat] = legendsubplots()
stat.description = [ 'Subplots with legends. ' , ...
'Increase value of "length" in the code to stress-test your TeX installation.' ];
stat.unreliable = isOctave; %FIXME: investigate
stat.issues = 609;
% size of upper subplot
rows = 4;
% number of points. A large number here (eg 1000) will stress-test
% matlab2tikz and your TeX installation. Be prepared for it to run out of
% memory
length = 100;
% generate some spurious data
t = 0:(4*pi)/length:4*pi;
x = t;
a = t;
y = sin(t) + 0.1*sin(134*t.^2);
b = sin(t) + 0.1*cos(134*t.^2) + 0.05*cos(2*t);
% plot the top figure
subplot(rows+2,1,1:rows);
% first line
sigma1 = std(y);
tracey = mean(y,1);
plot123 = plot(x,tracey,'b-');
hold on
% second line
sigma2 = std(b);
traceb = mean(b,1);
plot456 = plot(a,traceb,'r-');
spec0 = ['Mean V(t)_A (\sigma \approx ' num2str(sigma1,'%0.4f') ')'];
spec1 = ['Mean V(t)_B (\sigma \approx ' num2str(sigma2,'%0.4f') ')'];
hold off
%plot123(1:2)
legend([plot123; plot456],spec0,spec1)
legend boxoff
xlabel('Time/s')
ylabel('Voltage/V')
title('Time traces');
% now plot a differential trace
subplot(rows+2,1,rows+1:rows+2)
plot7 = plot(a,traceb-tracey,'k');
legend(plot7,'\Delta V(t)')
legend boxoff
xlabel('Time/s')
ylabel('\Delta V')
title('Differential time traces');
end
% =========================================================================
function [stat] = bodeplots()
stat.description = 'Bode plots with legends.';
stat.unreliable = isMATLAB(); % FIXME: inconsistent axis limits and
% tick positions; see #641 (issuecomment-106241711)
if isempty(which('tf'))
fprintf( 'function "tf" not found. Skipping.\n\n' );
stat.skip = true;
return
end
Rc=1;
C=1.5e-6; %F
% Set inductors
L1=4e-3;
L2=0.8e-3;
% Resistances of inductors
R1=4;
R2=2;
% Transfer functions
% Building transfer functions
s=tf('s');
Zc=1/(s*C)+Rc;
Z1=s*L1+R1;
Z2=s*L2+R2;
LCLd=(Z2+Zc)/(Z1+Zc);
LCL=(s^2*C*L2+1)/(s^2*C*L1+1);
t=logspace(3,5,1000);
bode(LCL,t)
hold on
bode(LCLd,t)
title('Voltage transfer function of a LCL filter')
set(findall(gcf,'type','line'),'linewidth',1.5)
grid on
legend('Perfect LCL',' Real LCL','Location','SW')
% Work around a peculiarity in MATLAB: when the figure is invisible,
% the XData/YData of all plots is NaN. It gets set to the proper values when
% the figure is actually displayed. To do so, we temporarily toggle this
% option. This triggers the call-back (and might flicker the figure).
isVisible = get(gcf,'visible');
set(gcf,'visible','on')
set(gcf,'visible',isVisible);
end
% =========================================================================
function [stat] = rlocusPlot()
stat.description = 'rlocus plot.';
stat.unreliable = isMATLAB(); % FIXME: radial grid is not present on all
% environments (see #641)
if isempty(which('tf'))
fprintf( 'function "tf" not found. Skipping.\n\n' );
stat.skip = true;
return
end
if isMATLAB('<', [8,4])
% in MATLAB R2014a and below, `rlocus` plots with no background color
% are not supported. So, force that color to white to work around
% that bug. Newer versions don't suffer from this.
set(gca, 'Color', 'w');
end
rlocus(tf([1 1],[4 3 1]))
% Work around a peculiarity in MATLAB: when the figure is invisible,
% the XData/YData of all plots is NaN. It gets set to the proper values when
% the figure is actually displayed. To do so, we temporarily toggle this
% option. This triggers the call-back (and might flicker the figure).
isVisible = get(gcf,'visible');
set(gcf,'visible','on')
set(gcf,'visible',isVisible);
end
% =========================================================================
function [stat] = mandrillImage()
stat.description = 'Picture of a mandrill.';
if ~exist('mandrill.mat','file')
fprintf( 'mandrill data set not found. Skipping.\n\n' );
stat.skip = true;
return
end
data = load( 'mandrill' );
image( data.X ) % show image
colormap( data.map ) % adapt colormap
axis image % pixels should be square
axis off % disable axis
end
% =========================================================================
function [stat] = besselImage()
stat.description = 'Bessel function.';
stat.unreliable = isOctave(); % FIXME (Travis differs from Linux/Mac octave)
nu = -5:0.25:5;
beta = 0:0.05:2.5;
m = length(beta);
n = length(nu);
trace = zeros(m,n);
for i=1:length(beta);
for j=1:length(nu)
if (floor(nu(j))==nu(j))
trace(i,j)=abs(besselj(nu(j),beta(i)));
end
end
end
imagesc(nu,beta,trace);
colorbar()
xlabel('Order')
ylabel('\beta')
set(gca,'YDir','normal')
end
% =========================================================================
function [stat] = clownImage()
stat.description = 'Picture of a clown.';
if ~exist('clown.mat','file')
fprintf( 'clown data set not found. Skipping.\n\n' );
stat.skip = true;
return
end
data = load( 'clown' );
imagesc( data.X )
colormap( gray )
end
% =========================================================================
function [stat] = zplanePlot1()
stat.description = 'Representation of the complex plane with zplane.';
stat.unreliable = isMATLAB('<', [8,4]); % FIXME: investigate
% check of the signal processing toolbox is installed
verInfo = ver('signal');
if isempty(verInfo) || isempty(verInfo.Name)
fprintf( 'Signal toolbox not found. Skip.\n\n' );
stat.skip = true;
return
end
[z,p] = ellip(4,3,30,200/500);
zplane(z,p);
title('4th-Order Elliptic Lowpass Digital Filter');
end
% =========================================================================
function [stat] = zplanePlot2()
stat.description = 'Representation of the complex plane with zplane.';
stat.unreliable = isMATLAB; % FIXME: #604; only difference is `width`
stat.closeall = true;
% check of the signal processing toolbox is installed
verInfo = ver('signal');
if isempty(verInfo) || isempty(verInfo.Name)
fprintf( 'Signal toolbox not found. Skip.\n\n' );
stat.skip = true;
return
end
[b,a] = ellip(4,3,30,200/500);
Hd = dfilt.df1(b,a);
zplane(Hd) % FIXME: This opens a new figure that doesn't get closed automatically
end
% =========================================================================
function [stat] = freqResponsePlot()
stat.description = 'Frequency response plot.';
stat.closeall = true;
stat.issues = [409];
stat.unreliable = isMATLAB(); % FIXME: investigate
% See also: https://github.com/matlab2tikz/matlab2tikz/pull/759#issuecomment-138477207
% and https://gist.github.com/PeterPablo/b01cbe8572a9e5989037 (R2014b)
% check of the signal processing toolbox is installed
verInfo = ver('signal');
if isempty(verInfo) || isempty(verInfo.Name)
fprintf( 'Signal toolbox not found. Skip.\n\n' );
stat.skip = true;
return
end
b = fir1(80,0.5,kaiser(81,8));
hd = dfilt.dffir(b);
freqz(hd); % FIXME: This opens a new figure that doesn't get closed automatically
end
% =========================================================================
function [stat] = axesLocation()
stat.description = 'Swapped axis locations.';
stat.issues = 259;
plot(cos(1:10));
set(gca,'XAxisLocation','top');
set(gca,'YAxisLocation','right');
end
% =========================================================================
function [stat] = axesColors()
stat.description = 'Custom axes colors.';
plot(sin(1:15));
set(gca,'XColor','g','YColor','b');
% set(gca,'XColor','b','YColor','k');
box off;
end
% =========================================================================
function [stat] = multipleAxes()
stat.description = 'Multiple axes.';
x1 = 0:.1:40;
y1 = 4.*cos(x1)./(x1+2);
x2 = 1:.2:20;
y2 = x2.^2./x2.^3;
line(x1,y1,'Color','r');
ax1 = gca;
set(ax1,'XColor','r','YColor','r')
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k','YColor','k');
line(x2,y2,'Color','k','Parent',ax2);
xlimits = get(ax1,'XLim');
ylimits = get(ax1,'YLim');
xinc = (xlimits(2)-xlimits(1))/5;
yinc = (ylimits(2)-ylimits(1))/5;
% Now set the tick mark locations.
set(ax1,'XTick',xlimits(1):xinc:xlimits(2) ,...
'YTick',ylimits(1):yinc:ylimits(2) )
end
% =========================================================================
function [stat] = scatterPlotRandom()
stat.description = 'Generic scatter plot.';
n = 1:100;
% MATLAB: Use the default area of 36 points squared. The units for the
% marker area is points squared.
% octave: If s is not given, [...] a default value of 8 points is used.
% Try obtain similar behavior and thus apply square root: sqrt(36) vs. 8
sArea = 1000*(1+cos(n.^1.5)); % scatter size in unit points squared
sRadius = sqrt(sArea*pi);
if isMATLAB()
s = sArea; % unit: points squared
elseif isOctave()
s = sRadius; % unit: points
end
scatter(n, n, s, n.^8);
colormap autumn;
end
% =========================================================================
function [stat] = scatterPlot()
stat.description = 'Scatter plot with MATLAB(R) stat.';
if ~exist('seamount.mat','file')
fprintf( 'seamount data set not found. Skipping.\n\n' );
stat.skip = true;
return
end
data = load( 'seamount' );
scatter( data.x, data.y, 5, data.z, '^' );
end
% =========================================================================
function [stat] = scatterPlotMarkers()
stat.description = 'Scatter plot with with different marker sizes and legend.';
% FIXME: octave: Output is empty?! Potentially fixed by #669
n = 1:10;
d = 10;
e = d * ones(size(n));
% MATLAB: Use the default area of 36 points squared. The units for the
% marker area is points squared.
% octave: If s is not given, [...] a default value of 8 points is used.
% Try obtain similar behavior and thus apply square root: sqrt(36) vs. 8
sArea = d^2 * n; % scatter size in unit points squared
sRadius = sqrt(sArea);
if isMATLAB()
s = sArea; % unit: points squared
elseif isOctave()
s = sRadius; % unit: points
end
grid on;
hold on;
style = {'bx','rd','go','c.','m+','y*','bs','mv','k^','r<','g>','cp','bh'};
names = {'bx','rd','go','c.','m plus','y star','bs','mv',...
'k up triangle','r left triangle','g right triangle','cp','bh'};
nStyles = numel(style);
for ii = 1:nStyles
curr = style{ii};
scatter(n, ii * e, s, curr(1), curr(2));
end
xlim([min(n)-1 max(n)+1]);
ylim([0 d*(nStyles+1)]);
set(gca,'XTick',n,'XTickLabel',sArea,'XTickLabelMode','manual');
end
% =========================================================================
function [stat] = scatter3Plot()
stat.description = 'Scatter3 plot with MATLAB(R) stat.';
[x,y,z] = sphere(16);
X = [x(:)*.5 x(:)*.75 x(:)];
Y = [y(:)*.5 y(:)*.75 y(:)];
Z = [z(:)*.5 z(:)*.75 z(:)];
S = repmat([1 .75 .5]*10,numel(x),1);
C = repmat([1 2 3],numel(x),1);
scatter3(X(:),Y(:),Z(:),S(:),C(:),'filled'), view(-60,60)
view(40,35)
end
% =========================================================================
function [stat] = spherePlot()
stat.description = 'Stretched sphere with unequal axis limits.';
stat.issues = 560;
sphere(30);
title('a sphere: x^2+y^2+z^2');
xlabel('x');
ylabel('y');
zlabel('z');
set(gca,'DataAspectRatio',[1,1,.5],'xlim',[-1 2], 'zlim',[-1 0.8])
end
% =========================================================================
function [stat] = surfPlot()
stat.description = 'Surface plot.';
[X,Y,Z] = peaks(30);
surf(X,Y,Z)
colormap hsv
axis([-3 3 -3 3 -10 5])
set(gca,'View',[-37.5,36]);
hc = colorbar('YTickLabel', ...
{'Freezing','Cold','Cool','Neutral',...
'Warm','Hot','Burning','Nuclear'});
set(get(hc,'Xlabel'),'String','Multitude');
set(get(hc,'Ylabel'),'String','Magnitude');
set(hc,'YTick',0:0.7:7);
set(hc,'YTickLabel',...
{'-0.8' '-0.6' '-0.4' '-0.2' '0.0' ...
'0.2' '0.4' '0.6' '0.8' '0.10' '0.12'});
set(get(hc,'Title'),...
'String', 'k(u,v)', ...
'FontSize', 12, ...
'interpreter', 'tex');
xlabel( 'x' )
ylabel( 'y' )
zlabel( 'z' )
end
% =========================================================================
function [stat] = surfPlot2()
stat.description = 'Another surface plot.';
stat.unreliable = isMATLAB || isOctave; % FIXME: investigate
z = [ ones(15, 5) zeros(15,5);
zeros(5, 5) zeros( 5,5)];
surf(abs(fftshift(fft2(z))) + 1);
set(gca,'ZScale','log');
legend( 'legendary', 'Location', 'NorthEastOutside' );
end
% =========================================================================
function [stat] = superkohle()
stat.description = 'Superkohle plot.';
stat.unreliable = isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
if ~exist('initmesh')
fprintf( 'initmesh() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
x1=0;
x2=pi;
y1=0;
y2=pi;
omegashape = [2 2 2 2 % 2 = line segment; 1 = circle segment; 4 = elipse segment
x1 x2 x2 x1 % start point x
x2 x2 x1 x1 % end point x
y1 y1 y2 y2 % start point y
y1 y2 y2 y1 % end point y
1 1 1 1
0 0 0 0];
[xy,edges,tri] = initmesh(omegashape,'Hgrad',1.05);
mmin = 1;
while size(xy,2) < mmin
[xy,edges,tri] = refinemesh(omegashape,xy,edges,tri);
end
m = size(xy,2);
x = xy(1,:)';
y = xy(2,:)';
y0 = cos(x).*cos(y);
pdesurf(xy,tri,y0(:,1));
title('y_0');
xlabel('x1 axis');
ylabel('x2 axis');
axis([0 pi 0 pi -1 1]);
grid on;
end
% =========================================================================
function [stat] = meshPlot()
stat.description = 'Mesh plot.';
[X,Y,Z] = peaks(30);
mesh(X,Y,Z)
colormap hsv
axis([-3 3 -3 3 -10 5])
xlabel( 'x' )
ylabel( 'y' )
zlabel( 'z' )
end
% =========================================================================
function [stat] = ylabels()
stat.description = 'Separate y-labels.';
x = 0:.01:2*pi;
H = plotyy(x,sin(x),x,3*cos(x));
ylabel(H(1),'sin(x)');
ylabel(H(2),'3cos(x)');
xlabel(H(1),'time');
end
% =========================================================================
function [stat] = spectro()
stat.description = 'Spectrogram plot';
stat.unreliable = isMATLAB('<', [8,4]); % FIXME: investigate
% In the original test case, this is 0:0.001:2, but that takes forever
% for LaTeX to process.
if isempty(which('chirp'))
fprintf( 'chirp() not found. Skipping.\n\n' );
stat.description = [];
stat.skip = true;
return
end
T = 0:0.005:2;
X = chirp(T,100,1,200,'q');
spectrogram(X,128,120,128,1E3);
title('Quadratic Chirp');
end
% =========================================================================
function [stat] = mixedBarLine()
stat.description = 'Mixed bar/line plot.';
stat.unreliable = isOctave; %FIXME: investigate (octave of egon)
% unreliable, see issue #614 (comment 92263263)
data = ACID_data;
x = data(:);
hist(x,10)
y = ylim;
hold on;
plot([mean(x) mean(x)], y, '-r');
hold off;
end
% =========================================================================
function [stat] = decayingharmonic()
stat.description = 'Decaying harmonic oscillation with \TeX{} title.';
stat.issues = 587;
% Based on an example from
% http://www.mathworks.com/help/techdoc/creating_plots/f0-4741.html#f0-28104
A = 0.25;
alpha = 0.007;
beta = 0.17;
t = 0:901;
y = A * exp(-alpha*t) .* sin(beta*t);
plot(t, y)
title('{\itAe}^{-\alpha\itt}sin\beta{\itt}, \alpha<<\beta, \beta>>\alpha, \alpha<\beta, \beta>\alpha, b>a')
xlabel('Time \musec.')
ylabel('Amplitude |X|')
end
% =========================================================================
function [stat] = texcolor()
stat.description = 'Multi-colored text using \TeX{} commands.';
% Taken from an example at
% http://www.mathworks.com/help/techdoc/creating_plots/f0-4741.html#f0-28104
text(.1, .5, ['\fontsize{16}black {\color{magenta}magenta '...
'\color[rgb]{0 .5 .5}teal \color{red}red} black again'])
end
% =========================================================================
function [stat] = textext()
stat.description = 'Formatted text and special characters using \TeX{}.';
% Taken from an example at
% http://www.mathworks.com/help/techdoc/creating_plots/f0-4741.html#f0-28303
txstr(1) = { 'Each cell is a quoted string' };
txstr(2) = { 'You can specify how the string is aligned' };
txstr(3) = { 'You can use LaTeX symbols like \pi \chi \Xi' };
txstr(4) = { '\bfOr use bold \rm\itor italic font\rm' };
txstr(5) = { '\fontname{courier}Or even change fonts' };
txstr(5) = { 'and use umlauts like äöüßÄÖÜ and accents éèêŐőŰűç' };
plot( 0:6, sin(0:6) )
text( 5.75, sin(2.5), txstr, 'HorizontalAlignment', 'right' )
end
% =========================================================================
function [stat] = texrandom()
stat.description = 'Random TeX symbols';
try
rng(42); %fix seed
%TODO: fully test tex conversion instead of a random subsample!
catch
rand('seed', 42); %#ok (this is deprecated in MATLAB)
end
num = 20; % number of symbols per line
symbols = {'\it', '\bf', '\rm', '\sl', ...
'\alpha', '\angle', '\ast', '\beta', '\gamma', '\delta', ...
'\epsilon', '\zeta', '\eta', '\theta', '\vartheta', ...
'\iota', '\kappa', '\lambda', '\mu', '\nu', '\xi', '\pi', ...
'\rho', '\sigma', '\varsigma', '\tau', '\equiv', '\Im', ...
'\otimes', '\cap', '{\int}', '\rfloor', '\lfloor', '\perp',...
'\wedge', '\rceil', '\vee', '\langle', '\upsilon', '\phi', ...
'\chi', '\psi', '\omega', '\Gamma', '\Delta', '\Theta', ...
'\Lambda', '\Xi', '\Pi', '\Sigma', '\Upsilon', '\Phi', ...
'\Psi', '\Omega', '\forall', '\exists', '\ni', '{\cong}', ...
'\approx', '\Re', '\oplus', '\cup', '\subseteq', '\lceil', ...
'\cdot', '\neg', '\times', '\surd', '\varpi', '\rangle', ...
'\sim', '\leq', '\infty', '\clubsuit', '\diamondsuit', ...
'\heartsuit', '\spadesuit', '\leftrightarrow', ...
'\leftarrow', '\Leftarrow', '\uparrow', '\rightarrow', ...
'\Rightarrow', '\downarrow', '\circ', '\pm', '\geq', ...
'\propto', '\partial', '\bullet', '\div', '\neq', ...
'\aleph', '\wp', '\oslash', '\supseteq', '\nabla', ...
'{\ldots}', '\prime', '\0', '\mid', '\copyright', ...
'\o', '\in', '\subset', '\supset', ...
'\_', '\^', '\{', '\}', '$', '%', '#', ...
'(', ')', '+', '-', '=', '/', ',', '.', '<', '>', ...
'!', '?', ':', ';', '*', '[', ']', '§', '"', '''', ...
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ...
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', ...
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', ...
'w', 'x', 'y', 'z', ...
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', ...
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', ...
'W', 'X', 'Y', 'Z' ...
};
% Note: Instead of '\ldots' the list of symbols contains the entry
% '{\ldots}'. This is because TeX gives an error if it
% encounters the sequence '$a_\ldots$' or '$a^\ldots$'. It
% looks like that is a TeX bug. Nevertheless this sequence
% could appear in the random output, therefore \ldots is
% wrapped in braces since '$a_{\ldots}$' and '$a^{\ldots}$'
% don't crash TeX.
% Same thing with '\cong' and '\int'.
% \color{red} etc. isn't included
% \fontname{Times} etc. isn't included
% \fontsize{12} etc. isn't included
switch getEnvironment
case 'MATLAB'
% MATLAB expects tilde and ampersand to be un-escaped and backslashes
% to be escaped
symbols = [ symbols, {'~', '&', '\\'} ];
case 'Octave'
% Octave expects tilde and ampersand to be escaped for regular
% output. If either are used un-escaped, that creates odd output in
% Octave itself, but since matlab2tikz should be able to handle
% those cases, let's include the un-escaped symbols in the list.
symbols = [ symbols, {'\~', '\&', '~', '&'} ];
% Octave's backslash handling is weird to say the least. However,
% matlab2tikz treats backslashes the same in Octave as it does in
% MATLAB. Therefore, let's add an escaped backslash to the list
symbols = [ symbols, {'\\'} ];
otherwise
error( 'Unknown environment. Need MATLAB(R) or Octave.' )
end
for ypos = [0.9:-.2:.1]
% Generate `num' random indices to the list of symbols
index = max(ceil(rand(1, num)*length(symbols)), 1);
% Assemble symbols into one cell string array
string = symbols(index);
% Add random amount of balanced braces in random positions to `string'.
% By potentially generating more than one set of braces randomly, it's
% possible to create more complex patterns of nested braces. Increase
% `braceprob' to get more braces, but don't use values greater than or
% equal 1 which would result in an infinite loop.
braceprob = 0.6;
while rand(1,1) < braceprob
% Generate two random numbers ranging from 1 to n with n = number
% of symbols in `string'
bracepos = max(ceil(rand(1, 2)*length(string)), 1);
% Modify `string' so that an opening brace is inserted before
% min(bracepos) symbols and a closing brace after max(bracepos)
% symbols. That way any number of symbols from one to all in
% `string' are wrapped in braces for min(bracepos) == max(bracepos)
% and min(bracepos) == 1 && max(bracepos) == length(string),
% respectively.
string = [string(1:min(bracepos)-1), {'{'}, ...
string(min(bracepos):max(bracepos)), ...
{'}'}, string(max(bracepos)+1:end) ];
end
% Clean up: remove '{}', '{{}}', etc.
clean = false;
while clean == false
clean = true;
for i = 1:length(string)-1
if strcmp( string(i), '{' ) && strcmp( string(i+1), '}' )
string = [string(1:i-1), string(i+2:end)];
clean = false;
break
end
end
end
% Subscripts '_' and superscripts '^' in TeX are tricky in that certain
% combinations are not allowed and there are some subtleties in regard
% to more complicated combinations of sub/superscripts:
% - ^a or _a at the beginning of a TeX math expression is permitted.
% - a^ or a_ at the end of a TeX math expression is not.
% - a__b, a_^b, a^_b, or a^^b is not allowed, as is any number of
% consecutive sub/superscript operators. Actually a^^b does not
% crash TeX, but it produces seemingly random output instead of `b',
% therefore it should be avoided, too.
% - a^b^c or a_b_c is not allowed as it results in a "double subscript/
% superscript" error.
% - a^b_c or a_b^c, however, does work.
% - a^bc^d or a_bc_d also works.
% - a^b_c^d or a_b^c_d is not allowed and results in a "double
% subscript/superscript" error.
% - a{_}b, a{^}b, {a_}b or {a^}b is not permitted.
% - a{_b} or a{^b} is valid TeX code.
% - {a_b}_c produces the same output as a_{bc}. Likewise for '^'.
% - a_{b_c} results in "a index b sub-index c". Likewise for '^'.
% - a^{b}^c or a_{b}_c is not allowed as it results in a "double
% subscript/superscript" error.
%
% From this we can derive a number of rules:
% 1) The last symbol in a TeX string must not be '^' or '_'.
% 2a) There must be at least one non-brace symbol between any '^' and '_'.
% 2b) There must be at least one non-brace symbol between any '_' and '^'.
% 3a) There must either be at least two non-brace, non-'_' symbols or at
% least one non-brace, non-'_' symbol and one brace (opening or
% closing) between any two '^'.
% 3b) There must either be at least two non-brace, non-'^' symbols or at
% least one brace (opening or closing) between any two '_'.
% 4) '^' or '_' must not appear directly before '}'.
% 5) '^' or '_' must not appear directly after '}'.
% 6) Whenever braces were mentioned, that refers to non-empty braces,
% i.e. '{}' counts as nothing. Printable/escaped braces '\{' and '\}'
% also don't count as braces but as regular symbols.
% 7) '^' or '_' must not appear directly before '\it', '\bf', '\rm', or
% '\sl'.
% 8) '^' or '_' must not appear directly after '\it', '\bf', '\rm', or
% '\sl'.
%
% A few test cases:
% Permitted: ^a... _a... a^b_c a_b^c a^bc^d a_bc_d a{_b} a{^b}
% {a_b}_c a_{bc} {a^b}^c a^{bc} a_{b_c} a^{b^c}
% Forbidden: ...z^ ...z_ a__b a_^b a^_b [a^^b] a^b^c a_b_c
% a^b_c^d a_b^c_d a{_}b a{^}b {a_}b {a^}b
% a^{_b} a_{^b} a^{b}^c a_{b}_c
%
% Now add sub/superscripts according to these rules
subsupprob = 0.1; % Probability for insertion of a sub/superscript
caretdist = Inf; % Distance to the last caret
underscdist = Inf; % Distance to the last underscore
bracedist = Inf; % Distance to the last brace (opening or closing)
pos = 0;
% Making sure the post-update `pos' in the while loop is less than the
% number of symbols in `string' enforces rule 1: The last symbol in
% a TeX string must not be '^' or '_'.
while pos+1 < length(string)
% Move one symbol further
pos = pos + 1;
% Enforce rule 7: No sub/superscript directly before '\it', '\bf',
% '\rm', or '\sl'.
if strcmp( string(pos), '\it' ) || strcmp( string(pos), '\bf' ) ...
|| strcmp( string(pos), '\rm' ) || strcmp( string(pos), '\sl' )
continue
end
% Enforce rule 8: No sub/superscript directly after '\it', '\bf',
% '\rm', or '\sl'.
if (pos > 1) ...
&& ( strcmp( string(pos-1), '\it' ) ...
|| strcmp( string(pos-1), '\bf' ) ...
|| strcmp( string(pos-1), '\rm' ) ...
|| strcmp( string(pos-1), '\sl' ) ...
)
continue
end
bracedist = bracedist + 1;
% Enforce rule 4: No sub/superscript directly before '}'
if strcmp( string(pos), '}' )
bracedist = 0; % Also update braces distance
continue
end
% Enforce rule 5: No sub/superscript directly after '}'
if (pos > 1) && strcmp( string(pos-1), '}' )
continue
end
% Update distances for either braces or caret/underscore depending
% on whether the symbol currently under scrutiny is a brace or not.
if strcmp( string(pos), '{' )
bracedist = 0;
else
caretdist = caretdist + 1;
underscdist = underscdist + 1;
end
% Generate two random numbers, then check if any of them is low
% enough, so that with probability `subsupprob' a sub/superscript
% operator is inserted into `string' at the current position. In
% case both random numbers are below the threshold, whether a
% subscript or superscript operator is to be inserted depends on
% which of the two numbers is smaller.
randomnums = rand(1, 2);
if min(randomnums) < subsupprob
if randomnums(1) < randomnums(2)
% Enforce rule 2b: There must be at least one non-brace
% symbol between previous '_' and to-be-inserted '^'.
if underscdist < 1
continue
end
% Enforce rule 3a: There must either be at least two
% non-brace, non-'_' symbols or at least one brace (opening
% or closing) between any two '^'.
if ~( ((caretdist >= 2) && (underscdist >= 2)) ...
|| ((bracedist < 2) && (caretdist >= 2)) )
continue
end
% Insert '^' before `pos'th symbol in `string' now that
% we've made sure all rules are honored.
string = [ string(1:pos-1), {'^'}, string(pos:end) ];
caretdist = 0;
pos = pos + 1;
else
% Enforce rule 2a: There must be at least one non-brace
% symbol between previous '^' and to-be-inserted '_'.
if caretdist < 1
continue
end
% Enforce rule 3b: There must either be at least two
% non-brace, non-'^' symbols or at least one brace (opening
% or closing) between any two '_'.
if ~( ((caretdist >= 2) && (underscdist >= 2)) ...
|| ((bracedist < 2) && (underscdist >= 2)) )
continue
end
% Insert '_' before `pos'th symbol in `string' now that
% we've made sure all rules are honored.
string = [ string(1:pos-1), {'_'}, string(pos:end) ];
underscdist = 0;
pos = pos + 1;
end
end
end % while pos+1 < length(string)
% Now convert the cell string array of symbols into one regular string
string = [string{:}];
% Print the string in the figure to be converted by matlab2tikz
text( .05, ypos, string, 'interpreter', 'tex' )
% And print it to the console, too, in order to enable analysis of
% failed tests
fprintf( 'Original string: %s\n', string )
end
title('Random TeX symbols \\\{\}\_\^$%#&')
end
% =========================================================================
function [stat] = latexInterpreter()
stat.description = '\LaTeX{} interpreter test (display math not working)';
stat.issues = 448;
stat.unreliable = isMATLAB('<=', [8,3]); %FIXME: broken since decd496 (mac vs linux)
plot(magic(3),'-x');
% Adapted from an example at
% http://www.mathworks.com/help/techdoc/ref/text_props.html#Interpreter
text(1.5, 2.0, ...
'$$\int_0^x\!\int_{\Omega} \mathrm{d}F(u,v) \mathrm{d}\omega$$', ...
'Interpreter', 'latex', ...
'FontSize', 26);
title(['display math old: $$\alpha$$ and $$\sum_\alpha^\Omega$$; ', ...
'inline math: $\alpha$ and $\sum_\alpha^\Omega$'],'Interpreter','latex');
end
% =========================================================================
function [stat] = latexmath2()
stat.description = 'Some nice-looking formulas typeset using the \LaTeX{} interpreter.';
stat.issues = 637;
% Adapted from an example at
% http://www.mathworks.com/help/techdoc/creating_plots/f0-4741.html#bq558_t
set(gcf, 'color', 'white')
set(gcf, 'units', 'inches')
set(gcf, 'position', [2 2 4 6.5])
set(gca, 'visible', 'off')
% Note: The matrices in h(1) and h(2) cannot be compiled inside pgfplots.
% They are therefore disabled.
% h(1) = text( 'units', 'inch', 'position', [.2 5], ...
% 'fontsize', 14, 'interpreter', 'latex', 'string', ...
% [ '$$\hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr' ...
% '3 & 5 & 7 \cr 4 & 9 & 2 } } \right)$$' ]);
% h(2) = text( 'units', 'inch', 'position', [.2 4], ...
% 'fontsize', 14, 'interpreter', 'latex', 'string', ...
% [ '$$\left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr' ...
% '\sin(\phi) & \cos(\phi) \cr}} \right]' ...
% '\left[ \matrix{x \cr y} \right]$$' ]);
h(3) = text( 'units', 'inches', 'position', [.2 3], ...
'fontsize', 14, 'interpreter', 'latex', 'string', ...
[ '$$L\{f(t)\} \equiv F(s) = \int_0^\infty\!\!{e^{-st}' ...
'f(t)dt}$$' ]);
h(4) = text( 'units', 'inches', 'position', [.2 2], ...
'fontsize', 14, 'interpreter', 'latex', 'string', ...
'$$e = \sum_{k=0}^\infty {\frac{1}{k!}} $$' );
h(5) = text( 'units', 'inches', 'position', [.2 1], ...
'fontsize', 14, 'interpreter', 'latex', 'string', ...
[ '$$m \ddot y = -m g + C_D \cdot {\frac{1}{2}}' ...
'\rho {\dot y}^2 \cdot A$$' ]);
h(6) = text( 'units', 'inches', 'position', [.2 0], ...
'fontsize', 14, 'interpreter', 'latex', 'string', ...
'$$\int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}$$' );
end
% =========================================================================
function [stat] = parameterCurve3d()
stat.description = 'Parameter curve in 3D with text boxes in-/outside axis.';
stat.issues = [378, 790] ;
t = linspace(0, 20*pi, 1e5);
plot3(t, sin(t), 50 * cos(t));
text(0.5, 0.5, 10, 'text inside axis limits');
text(5.0, 1.5, 50, 'text outside axis (will be removed by cleanfigure())');
end
% =========================================================================
function [stat] = parameterSurf()
stat.description = 'Parameter and surface plot.';
stat.unreliable = isMATLAB('<', [8,4]); % FIXME: investigate
if ~exist('TriScatteredInterp')
fprintf( 'TriScatteredInterp() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
t = (1:100).';
t1 = cos(5.75352*t).^2;
t2 = abs(sin(t));
x = t1*4 - 2;
y = t2*4 - 2;
z = x.*exp(-x.^2 - y.^2);
%TODO: do we really need this TriScatteredInterp?
% It will be removed from MATLAB
% Construct the interpolant
F = TriScatteredInterp(x,y,z,'linear');
% Evaluate the interpolant at the locations (qx, qy), qz
% is the corresponding value at these locations.
ti = -2:.25:2;
[qx,qy] = meshgrid(ti,ti);
qz = F(qx,qy);
hold on
surf(qx,qy,qz)
plot3(x,y,z,'o')
view(gca,[-69 14]);
hold off
end
% =========================================================================
function [stat] = fill3plot()
stat.description = 'fill3 plot.';
if ~exist('fill3','builtin')
fprintf( 'fill3() not found. Skipping.\n\n' );
stat.skip = true;
return
end
x1 = -10:0.1:10;
x2 = -10:0.1:10;
p = sin(x1);
d = zeros(1,numel(p));
d(2:2:end) = 1;
h = p.*d;
grid on;
fill3(x1,x2,h,'k');
view(45,22.5);
box on;
end
% =========================================================================
function [stat] = rectanglePlot()
stat.unreliable = isMATLAB('<=', [8,3]); %FIXME: #749 (Jenkins)
stat.description = 'Rectangle handle.';
rectangle('Position', [0.59,0.35,3.75,1.37],...
'Curvature', [0.8,0.4],...
'LineWidth', 2, ...
'LineStyle', '--' ...
);
daspect([1,1,1]);
end
% =========================================================================
function [stat] = herrorbarPlot()
stat.description = 'herrorbar plot.';
% FIXME: octave is missing the legend
hold on;
X = 1:10;
Y = 1:10;
err = repmat(0.2, 1, 10);
h1 = errorbar(X, Y, err+X/30, 'r');
h_vec = herrorbar(X, Y, err);
for h=h_vec
set(h, 'color', [1 0 0]);
end
h2 = errorbar(X, Y+1, err, 'g');
h_vec = herrorbar(X, Y+1, err+Y/40);
for h=h_vec
set(h, 'color', [0 1 0]);
end
legend([h1 h2], {'test1', 'test2'})
end
% =========================================================================
function [stat] = hist3d()
stat.description = '3D histogram plot.';
if ~exist('hist3','builtin') && isempty(which('hist3'))
fprintf( 'Statistics toolbox not found. Skipping.\n\n' );
stat.skip = true;
return
end
% load carbig
% X = [MPG,Weight];
% hist3(X,[7 7]);
% xlabel('MPG'); ylabel('Weight');
% set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');
load carbig
X = [MPG,Weight];
hist3(X,[7 7]);
xlabel('MPG'); ylabel('Weight');
hist3(X,[7 7],'FaceAlpha',.65);
xlabel('MPG'); ylabel('Weight');
% Linux crashed with OpenGL.
%%set(gcf,'renderer','opengl');
% load seamount
% dat = [-y,x]; % Grid corrected for negative y-values
% n = hist3(dat); % Extract histogram data;
% % default to 10x10 bins
% view([-37.5, 30]);
end
% =========================================================================
function [stat] = myBoxplot()
stat.description = 'Boxplot.';
stat.unreliable = isMATLAB('<', [8,4]); % R2014a; #552 #414
if ~exist('boxplot','builtin') && isempty(which('boxplot'))
fprintf( 'Statistics toolbox not found. Skipping.\n\n' );
stat.skip = true;
return
end
errors =[
0.810000 3.200000 0.059500
0.762500 -3.200000 0.455500
0.762500 4.000000 0.901000
0.762500 3.600000 0.406000
0.192500 3.600000 0.307000
0.810000 -3.600000 0.604000
1.000000 -2.400000 0.505000
0.430000 -2.400000 0.455500
1.000000 3.200000 0.158500
];
boxplot(errors);
end
% =========================================================================
function [stat] = areaPlot()
stat.description = 'Area plot.';
M = magic(5);
M = M(1:3,2:4);
h = area(1:3, M);
legend(h([1,3]),'foo', 'foobar');
end
% =========================================================================
function [stat] = customLegend()
stat.description = 'Custom legend.';
stat.unreliable = isMATLAB('<', [8,4]) || isOctave; %FIXME: investigate (Travis differs from Linux/Mac octave)
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs');
lh=legend('y',4);
set(lh,'color','g')
set(lh,'edgecolor','r')
set(lh, 'position',[.5 .6 .1 .05])
end
% =========================================================================
function [stat] = pixelLegend()
stat.description = 'Legend with pixel position.';
x = linspace(0,1);
plot(x, [x;x.^2]);
set(gca, 'units', 'pixels')
lh=legend('1', '2');
set(lh, 'units','pixels','position', [100 200 65 42])
end
% =========================================================================
function [stat] = croppedImage()
stat.description = 'Custom legend.';
if ~exist('flujet.mat','file')
fprintf( 'flujet data set not found. Skipping.\n\n' );
stat.skip = true;
return;
end
load('flujet','X','map');
image(X)
colormap(map)
%axis off
axis image
xlim([50 200])
ylim([50 200])
% colorbar at top
colorbar('north');
set(gca,'Units','normalized');
end
% =========================================================================
function [stat] = pColorPlot()
stat.description = 'pcolor() plot.';
ylim([-1 1]); xlim([-1 1]); hold on; % prevent error on octave
n = 6;
r = (0:n)'/n;
theta = pi*(-n:n)/n;
X = r*cos(theta);
Y = r*sin(theta);
C = r*cos(2*theta);
pcolor(X,Y,C)
axis equal tight
end
% =========================================================================
function [stat] = multiplePatches()
stat.description = 'Multiple patches.';
xdata = [2 2 0 2 5;
2 8 2 4 5;
8 8 2 4 8];
ydata = [4 4 4 2 0;
8 4 6 2 2;
4 0 4 0 0];
cdata = [15 0 4 6 10;
1 2 5 7 9;
2 3 0 8 3];
p = patch(xdata,ydata,cdata,'Marker','o',...
'MarkerFaceColor','flat',...
'FaceColor','none');
end
% =========================================================================
function [stat] = hgTransformPlot()
stat.description = 'hgtransform() plot.';
if isOctave
% Octave (3.8.0) has no implementation of `hgtransform`
stat.skip = true;
return;
end
% Check out
% http://www.mathworks.de/de/help/matlab/ref/hgtransform.html.
ax = axes('XLim',[-2 1],'YLim',[-2 1],'ZLim',[-1 1]);
view(3);
grid on;
axis equal;
[x,y,z] = cylinder([.2 0]);
h(1) = surface(x,y,z,'FaceColor','red');
h(2) = surface(x,y,-z,'FaceColor','green');
h(3) = surface(z,x,y,'FaceColor','blue');
h(4) = surface(-z,x,y,'FaceColor','cyan');
h(5) = surface(y,z,x,'FaceColor','magenta');
h(6) = surface(y,-z,x,'FaceColor','yellow');
t1 = hgtransform('Parent',ax);
t2 = hgtransform('Parent',ax);
set(h,'Parent',t1);
h2 = copyobj(h,t2);
Txy = makehgtform('translate',[-1.5 -1.5 0]);
set(t2,'Matrix',Txy)
drawnow
end
% =========================================================================
function [stat] = logbaseline()
stat.description = 'Logplot with modified baseline.';
bar([0 1 2], [1 1e-2 1e-5],'basevalue', 1e-6);
set(gca,'YScale','log');
end
% =========================================================================
function [stat] = alphaImage()
stat.description = 'Images with alpha channel.';
stat.unreliable = isOctave; %FIXME: investigate
subplot(2,1,1);
title('Scaled Alpha Data');
N = 20;
h_imsc = imagesc(repmat(1:N, N, 1));
mask = zeros(N);
mask(N/4:3*N/4, N/4:3*N/4) = 1;
set(h_imsc, 'AlphaData', double(~mask));
set(h_imsc, 'AlphaDataMapping', 'scaled');
set(gca, 'ALim', [-1,1]);
title('');
subplot(2,1,2);
title('Integer Alpha Data');
N = 2;
line([0 N]+0.5, [0 N]+0.5, 'LineWidth', 2, 'Color','k');
line([0 N]+0.5, [N 0]+0.5, 'LineWidth', 2, 'Color','k');
hold on
imagesc([0,1;2,3],'AlphaData',uint8([64,128;192,256]))
end
% =========================================================================
function stat = annotationAll()
stat.description = 'All possible annotations with edited properties';
stat.unreliable = isMATLAB('<', [8,4]); % TODO: R2014a and older: #604
if isempty(which('annotation'))
fprintf( 'annotation() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
% Create plot
X1 = -5:0.1:5;
plot(X1,log(X1.^2+1));
% Create line
annotation('line',[0.21 0.26], [0.63 0.76], 'Color',[0.47 0.3 0.44],...
'LineWidth',4, 'LineStyle',':');
% Create arrow
if isOctave('>=', 4)
headStyle = 'vback3'; %Octave does not support cback2 yet (2015-09)
else
headStyle = 'cback2';
end
annotation('arrow',[0.25 0.22], [0.96 0.05], 'LineStyle','-.',...
'HeadStyle', headStyle);
% Create textarrow
annotation('textarrow',[0.46 0.35], [0.41 0.50],...
'Color',[0.92 0.69 0.12], 'TextBackgroundColor',[0.92 0.83 0.83],...
'String',{'something'}, 'LineWidth',2, 'FontWeight','bold',...
'FontSize',20, 'FontName','Helvetica');
% Create doublearrow
annotation('doublearrow',[0.33 0.7], [0.56 0.55]);
% Create textbox
annotation('textbox', [0.41 0.69 0.17 0.10], 'String',{'something'},...
'FitBoxToText','off');
% Create ellipse
if isOctave(4)
colorSpec = 'EdgeColor';
else
colorSpec = 'Color';
end
annotation('ellipse', [0.70 0.44 0.15 0.51], ...
colorSpec, [0.63 0.07 0.18],...
'LineWidth', 3, 'FaceColor',[0.80 0.87 0.96]);
% Create rectangle
annotation('rectangle', [0.3 0.26 0.53 0.58], 'LineWidth',8,...
'LineStyle',':');
end
% =========================================================================
function [stat] = annotationSubplots()
stat.description = 'Annotated and unaligned subplots';
if isempty(which('annotation'))
fprintf( 'annotation() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
X1 = 0:0.01:1;
Y1 = X1.^2;
Y2 = Y1.^2;
Y3 = X1.^(1/4);
set(gcf, 'Position', [100 100 1500 600]);
axes1 = axes('Parent',gcf, 'Position',[0.07 0.4015 0.2488 0.5146]);
box(axes1,'on');
hold(axes1,'all');
title('f(x)=x^2');
plot(X1,Y1,'Parent',axes1, 'DisplayName','(0:0.05:1).^2 vs 0:0.05:1');
axes2 = axes('Parent',gcf, 'OuterPosition',[0.4062 0 0.2765 0.6314]);
box(axes2,'on');
hold(axes2,'all');
plot(X1,Y2,'Parent',axes2,'DisplayName','(0:0.05:1).^4 vs 0:0.05:1');
axes3 = axes('Parent',gcf, 'Position',[0.7421 0.3185 0.21 0.5480]);
box(axes3,'on');
hold(axes3,'all');
plot(X1,Y3,'Parent',axes3,'DisplayName','(0:0.05:1).^(1/4) vs 0:0.05:1');
annotation(gcf,'textbox',[0.3667 0.5521 0.0124 0.0393], ...
'String',{'f^2'}, 'FitBoxToText','off');
annotation(gcf,'arrow',[0.3263 0.4281], [0.6606 0.3519]);
annotation(gcf,'textarrow',[0.6766 0.7229], [0.3108 0.6333],...
'TextEdgeColor','none', 'HorizontalAlignment','center', ...
'String',{'invert'});
end
% =========================================================================
function [stat] = annotationText()
stat.description = 'Variations of textual annotations';
stat.unreliable = isMATLAB('<', [8,4]); % FIXME: investigate
if ~exist('annotation')
fprintf( 'annotation() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
X1 = -5:0.1:5;
Y1 = log(X1.^2+1);
% Resize figure to fit all text inside
set(gcf,'Position', [100 100 1000 700]);
% Otherwise the axes is plotted wrongly
drawnow();
% Create axes
axes1 = axes('Parent',gcf);
hold(axes1,'all');
% Create plot
plot(X1,Y1);
% Create text
text('Parent',axes1,'String',' \leftarrow some point on the curve',...
'Position',[-2.01811125485123 1.5988219895288 7.105427357601e-15]);
% Create text
text('Parent',axes1,'String','another point \rightarrow',...
'Position',[1 0.693147180559945 0],...
'HorizontalAlignment','right');
% Create textbox
annotation(gcf,'textbox',...
[0.305611222444885 0.292803442287824 0.122244488977956 0.0942562592047128],...
'String',{'This boxes size','should adjust to','the text size'});
% Create textbox
annotation(gcf,'textbox',...
[0.71643086172344 0.195876288659794 0.10020240480962 0.209240982129118],...
'String',{'Multiple Lines due to fixed width'},...
'FitBoxToText','off');
% Create textbox
annotation(gcf,'textbox',...
[0.729456913827655 0.608247422680412 0.0851723446893787 0.104257797902974],...
'String',{'Overlapping','and italic'},...
'FontAngle','italic',...
'FitBoxToText','off',...
'BackgroundColor',[0.756862759590149 0.866666674613953 0.776470601558685]);
% Create textbox
annotation(gcf,'textbox',...
[0.420000437011093 0.680170575692964 0.155149863590109 0.192171438527209],...
'VerticalAlignment','middle',...
'String',{'Text with a','thick and','dotted','border'},...
'HorizontalAlignment','center',...
'FitBoxToText','off',...
'LineStyle',':',...
'LineWidth',4);
% Create textarrow
annotation(gcf,'textarrow',[0.21943887775551 0.2625250501002],...
[0.371002132196162 0.235640648011782],'TextEdgeColor','none',...
'TextBackgroundColor',[0.678431391716003 0.921568632125854 1],...
'TextRotation',30,...
'VerticalAlignment','bottom',...
'HorizontalAlignment','center',...
'String',{'Rotated Text'});
% Create textarrow
annotation(gcf,'textarrow',[0.238436873747493 0.309619238476953],...
[0.604315828808828 0.524300441826215],'TextEdgeColor','none',...
'TextColor',[1 1 1],...
'TextBackgroundColor',[0 0 1],...
'TextRotation',30,...
'VerticalAlignment','bottom',...
'HorizontalAlignment','center',...
'String',{'Rotated Text 2'},...
'HeadStyle','diamond',...
'Color',[1 0 0]);
end
% =========================================================================
function [stat] = annotationTextUnits()
stat.description = 'Text with changed Units';
stat.unreliable = isMATLAB('<', [8,4]); % FIXME: investigate
if ~exist('annotation')
fprintf( 'annotation() not found. Skipping.\n\n' );
stat.skip = true;
return;
end
X1 = -5:0.1:5;
Y1 = log(X1.^2+1);
% Resize figure to fit all text inside
set(gcf,'Units', 'inches');
set(gcf,'Position', [1.03125, 1.03125, 10.416666666666666, 7.291666666666666 ]);
% Otherwise the axes is plotted wrongly
drawnow();
% Create axes
axes1 = axes('Parent',gcf,'Units','centimeters',...
'Position',[3.4369697916666664, 2.035743645833333 20.489627604166664 15.083009739583332]);
hold(axes1,'all');
% Create plot
plot(X1,Y1);
% Create text
text('Parent',axes1,'Units','normalized',...
'String',' \leftarrow some point on the curve',...
'Position',[0.295865633074935 0.457364341085271 0]);
% Create text
text('Parent',axes1,'Units','centimeters',...
'String','another point \rightarrow',...
'Position',[12.2673383333333 2.98751989583333 0],...
'HorizontalAlignment','right');
% Create textbox
annotation(gcf,'textbox',...
[0.305611222444885 0.292803442287824 0.122244488977956 0.0942562592047128],...
'String',{'This boxes size','should adjust to','the text size'},...
'FitBoxToText','off',...
'Units','pixels');
% Create textarrow
annotation(gcf,'textarrow',[0.21943887775551 0.2625250501002],...
[0.371002132196162 0.235640648011782],'TextEdgeColor','none',...
'TextBackgroundColor',[0.678431391716003 0.921568632125854 1],...
'TextRotation',30,...
'HorizontalAlignment','center',...
'String',{'Rotated Text'},...
'Units','points');
% Create textarrow
annotation(gcf,'textarrow',[0.238436873747493 0.309619238476953],...
[0.604315828808828 0.524300441826215],'TextEdgeColor','none',...
'TextColor',[1 1 1],...
'TextBackgroundColor',[0 0 1],...
'TextRotation',30,...
'HorizontalAlignment','center',...
'String',{'Rotated Text 2'},...
'HeadStyle','diamond',...
'Color',[1 0 0]);
% Create textbox
if ~isOctave(4)
annotation(gcf,'textbox',...
[0.71643086172344 0.195876288659794 0.10020240480962 0.209240982129118],...
'String',{'Multiple Lines due to fixed width'},...
'FitBoxToText','off',...
'Units','characters');
else
% Octave 4 doesn't seem to like the "'Units','Characters'" in there
% so just remove the object altogether.
% This is strange, since it is documented: https://www.gnu.org/software/octave/doc/interpreter/Plot-Annotations.html#Plot-Annotations
end
% Create textbox
annotation(gcf,'textbox',...
[0.420000437011093 0.680170575692964 0.155149863590109 0.192171438527209],...
'VerticalAlignment','middle',...
'String',{'Text with a','thick and','dotted','border'},...
'HorizontalAlignment','center',...
'FitBoxToText','off',...
'LineStyle',':',...
'LineWidth',4);
% Create textbox
annotation(gcf,'textbox',...
[0.729456913827655 0.608247422680412 0.0851723446893787 0.104257797902974],...
'String',{'Overlapping','and italic'},...
'FontAngle','italic',...
'FitBoxToText','off',...
'BackgroundColor',[0.756862759590149 0.866666674613953 0.776470601558685]);
end
% =========================================================================
function [stat] = imageOrientation_inline()
% Run test and save pictures as inline TikZ code
[stat] = imageOrientation(false);
stat.unreliable = isOctave; % FIXME
end
function [stat] = imageOrientation_PNG()
% Run test and save pictures as external PNGs
[stat] = imageOrientation(true);
stat.unreliable = isOctave; % FIXME
end
function [stat] = imageOrientation(imagesAsPng)
% Parameter 'imagesAsPng' is boolean
stat.description = ['Systematic test of different axis', ...
' orientations and visibility (imagesAsPng = ', ...
num2str(imagesAsPng), ').'];
stat.extraOptions = {'imagesAsPng', imagesAsPng};
data = magic(3);
data = [[0,0,9]; data]; % ensure non-quadratic matrix
subplot(3,2,1);
imagesc(data); colormap(hot);
set(gca,'XDir','normal');
xlabel('XDir normal');
set(gca,'YDir','normal');
ylabel('YDir normal');
subplot(3,2,2);
imagesc(data); colormap(hot);
set(gca,'XDir','reverse');
xlabel('XDir reverse');
set(gca,'YDir','normal');
ylabel('YDir normal');
subplot(3,2,3);
imagesc(data); colormap(hot);
set(gca,'XDir','normal');
xlabel('XDir normal');
set(gca,'YDir','reverse');
ylabel('YDir reverse');
subplot(3,2,4);
imagesc(data); colormap(hot);
set(gca,'XDir','reverse');
xlabel('XDir reverse');
set(gca,'YDir','reverse');
ylabel('YDir reverse');
subplot(3,2,5);
imagesc(data); colormap(hot);
set(gca,'XDir','normal');
xlabel('XDir normal');
set(gca,'YDir','reverse');
ylabel('YDir reverse');
axis off;
title('like above, but axis off');
subplot(3,2,6);
imagesc(data); colormap(hot);
set(gca,'XDir','reverse');
xlabel('XDir reverse');
set(gca,'YDir','reverse');
ylabel('YDir reverse');
axis off;
title('like above, but axis off');
end
% =========================================================================
function [stat] = texInterpreter()
stat.description = 'Combinations of tex commands';
axes
text(0.1,0.9, {'\bfBold text before \alpha and also afterwards.', 'Even the next line is bold \itand a bit italic.'});
text(0.1,0.75, {'Changing \bfthe\fontname{Courier} font or \color[rgb]{0,0.75,0}color doesn''t', 'change the style. Resetting \rmthe style', 'doesn''t change the font or color.'});
text(0.1,0.6, 'Styles can be {\bflimited} using \{ and \}.');
text(0.1,0.45, {'But what happens to the output if there is', '{\bfuse an \alpha inside} the limitted style.'});
text(0.1,0.3, 'Or if the\fontsize{14} size\color{red} and color are \fontsize{10}changed at different\color{blue} points.');
text(0.1,0.15, {'Also_{some \bf subscripts} and^{superscripts} are possible.', 'Without brackets, it l^o_oks like t_his.' });
end
% =========================================================================
function [stat] = stackedBarsWithOther()
stat.description = 'stacked bar plots and other plots';
stat.issues = [442,648];
stat.unreliable = isOctave || isMATLAB(); % FIXME: #614
% details: https://github.com/matlab2tikz/matlab2tikz/pull/614#issuecomment-91844506
% dataset stacked
data = ACID_data;
Y = round(abs(data(7:-1:3,1:3))/10);
n = size(Y,1);
xVals = (1:n).';
yVals = min((xVals).^2, sum(Y,2));
subplot(2,1,1); hold on;
bar(Y,'stacked');
plot(xVals, yVals, 'Color', 'r', 'LineWidth', 2);
legend('show');
subplot(2,1,2); hold on;
b2 = barh(Y,'stacked','BarWidth', 0.75);
plot(yVals, xVals, 'Color', 'b', 'LineWidth', 2);
set(b2(1),'FaceColor','c','EdgeColor','none')
end
% =========================================================================
function [stat] = colorbarLabelTitle()
stat.description = 'colorbar with label and title';
stat.unreliable = isOctave; %FIXME: investigate
stat.issues = 429;
% R2014b handles colorbars smart: `XLabel` and `YLabel` merged into `Label`
% Use colormap 'jet' to create comparable output with MATLAB R2014b
% * Check horizontal/vertical colorbar (subplots)
% * Check if 'direction' is respected
% * Check if multiline label and title works
% * Check if latex interpreter works in label and title
subplot(1,2,1)
imagesc(magic(3));
hc = colorbar;
colormap('jet');
title(hc,'title $\beta$','Interpreter','latex');
ylabel(hc,'label $a^2$','Interpreter','latex');
set(hc,'YDir','reverse');
subplot(1,2,2)
label_multiline = {'first','second','third'};
title_multiline = {'title 1','title 2'};
imagesc(magic(3));
hc = colorbar('southoutside');
colormap('jet');
title(hc,title_multiline);
xlabel(hc,label_multiline);
end
% =========================================================================
function [stat] = textAlignment()
stat.description = 'alignment of text boxes and position relative to axis';
stat.issues = 378;
stat.unreliable = isOctave; %FIXME: investigate
plot([0.0 2.0], [1.0 1.0],'k'); hold on;
plot([0.0 2.0], [0.5 0.5],'k');
plot([0.0 2.0], [1.5 1.5],'k');
plot([1.0 1.0], [0.0 2.0],'k');
plot([1.5 1.5], [0.0 2.0],'k');
plot([0.5 0.5], [0.0 2.0],'k');
text(1.0,1.0,'h=c, v=m', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
text(1.5,1.0,'h=l, v=m', ...
'HorizontalAlignment','left','VerticalAlignment','middle');
text(0.5,1.0,'h=r, v=m', ...
'HorizontalAlignment','right','VerticalAlignment','middle');
text(0.5,1.5,'h=r, v=b', ...
'HorizontalAlignment','right','VerticalAlignment','bottom');
text(1.0,1.5,'h=c, v=b', ...
'HorizontalAlignment','center','VerticalAlignment','bottom');
text(1.5,1.5,'h=l, v=b', ...
'HorizontalAlignment','left','VerticalAlignment','bottom');
text(0.5,0.5,'h=r, v=t', ...
'HorizontalAlignment','right','VerticalAlignment','top');
text(1.0,0.5,'h=c, v=t', ...
'HorizontalAlignment','center','VerticalAlignment','top');
h_t = text(1.5,0.5,{'h=l, v=t','multiline'}, ...
'HorizontalAlignment','left','VerticalAlignment','top');
set(h_t,'BackgroundColor','g');
text(0.5,2.1, 'text outside axis (will be removed by cleanfigure())');
text(1.8,0.7, {'text overlapping', 'axis limits'});
text(-0.2,0.7, {'text overlapping', 'axis limits'});
text(0.9,0.0, {'text overlapping', 'axis limits'});
h_t = text(0.9,2.0, {'text overlapping', 'axis limits'});
% Set different units to test if they are properly handled
set(h_t, 'Units', 'centimeters');
end
% =========================================================================
function [stat] = overlappingPlots()
stat.description = 'Overlapping plots with zoomed data and varying background.';
stat.unreliable = isMATLAB();
% FIXME: this test is unreliable because the automatic axis limits of `ax2`
% differ on different test platforms. Reckon this by creating the figure
% using `ACID(97)` and then manually slightly modify the window size.
% We should not set the axis limits explicitly rather find a better way.
% Workaround: Slightly adapt width and height of `ax2`.
% #591, #641 (issuecomment-106241711)
stat.issues = 6;
% create pseudo random data and convert it from matrix to vector
l = 256;
l_zoom = 64;
wave = sin(linspace(1,10*2*pi,l));
% plot data
ax1 = axes();
plot(ax1, wave);
% overlapping plots with zoomed data
ax3 = axes('Position', [0.2, 0.6, 0.3, 0.4]);
ax4 = axes('Position', [0.7, 0.2, 0.2, 0.4]);
ax2 = axes('Position', [0.25, 0.3, 0.3, 0.4]);
plot(ax2, 1:l_zoom, wave(1:l_zoom), 'r');
plot(ax3, 1:l_zoom, wave(1:l_zoom), 'k');
plot(ax4, 1:l_zoom, wave(1:l_zoom), 'k');
% set x-axis limits of main plot and first subplot
xlim(ax1, [1,l]);
xlim(ax3, [1,l_zoom]);
% axis background color: ax2 = default, ax3 = green, ax4 = transparent
set(ax3, 'Color', 'green');
set(ax4, 'Color', 'none');
end
% =========================================================================
function [stat] = histogramPlot()
if isOctave || isMATLAB('<', [8,4])
% histogram() was introduced in Matlab R2014b.
% TODO: later replace by 'isHG2()'
fprintf('histogram() not found. Skipping.\n' );
stat.skip = true;
return;
end
stat.description = 'overlapping histogram() plots and custom size bins';
stat.issues = 525;
x = [-0.2, -0.484, 0.74, 0.632, -1.344, 0.921, -0.598, -0.727,...
-0.708, 1.045, 0.37, -1.155, -0.807, 1.027, 0.053, 0.863,...
1.131, 0.134, -0.017, -0.316];
y = x.^2;
edges = [-2 -1:0.25:3];
histogram(x,edges);
hold on
h = histogram(y);
set(h, 'orientation', 'horizontal');
end
% =========================================================================
function [stat] = alphaTest()
stat.description = 'overlapping objects with transparency and other properties';
stat.issues = 593;
contourf(peaks(5)); hold on; % background
% rectangular patch with different properties
h = fill([2 2 4 4], [2 3 3 2], 'r');
set(h, 'FaceColor', 'r');
set(h, 'FaceAlpha', 0.2);
set(h, 'EdgeColor', 'g');
set(h, 'EdgeAlpha', 0.4);
set(h, 'LineStyle', ':');
set(h, 'LineWidth', 4);
set(h, 'Marker', 'x');
set(h, 'MarkerSize', 16);
set(h, 'MarkerEdgeColor', [1 0.5 0]);
set(h, 'MarkerFaceColor', [1 0 0]); % has no visual effect
% line with different properties
h = line([3 3.5], [1.5 3.5]);
set(h, 'Color', [1 1 1]);
if isMATLAB('>=', [8,4])
% TODO: later replace by 'isHG2()'
fprintf('Note: RGBA (with alpha channel) only in HG2.\n' );
set(h, 'Color', [1 1 1 0.3]);
end
set(h, 'LineStyle', ':');
set(h, 'LineWidth', 6);
set(h, 'Marker', 'o');
set(h, 'MarkerSize', 14);
set(h, 'MarkerEdgeColor', [1 1 0]);
set(h, 'MarkerFaceColor', [1 0 0]);
end
% =========================================================================
function [stat] = removeOutsideMarker()
stat.description = 'remove markers outside of the box';
stat.issues = 788;
% Create the data and plot it
xdata = -1 : 0.5 : 1.5;
ydata_marker = 1.5 * ones(size(xdata));
ydata_line = 1 * ones(size(xdata));
ydata_combined = 0.5 * ones(size(xdata));
plot(xdata, ydata_marker, '*', ...
xdata, ydata_line, '-', ...
xdata, ydata_combined, '*-');
title('Markers at -1 and 0.5 should be removed, the line shortened');
% Change the limits, so one marker is outside the box
ylim([0, 2]);
xlim([0, 2]);
% Remove it
cleanfigure;
% Change the limits back to check result
xlim([-1, 2]);
end
% =========================================================================
function [stat] = colorbars()
stat.description = 'Manual positioning of colorbars';
stat.issues = [933 937];
stat.unreliable = isOctave(); %FIXME: positions differ between Octave 3.2 and 4.0.
shift = [0.2 0.8 0.2 0.8];
axLoc = {'in','out','out','in'};
for iAx = 1:4
hAx(iAx) = subplot(2,2,iAx);
axPos = get(hAx(iAx), 'Position');
cbPos = [axPos(1)+shift(iAx)*axPos(3), axPos(2), 0.02, 0.2];
hCb(iAx) = colorbar('Position', cbPos);
try
% only in HG2
set(hCb(iAx), 'AxisLocation', axLoc{iAx});
end
title(['AxisLocation = ' axLoc{iAx}]);
grid('on');
end
end
% =========================================================================
function [stat] = colorbarManualLocationRightOut()
stat.description = 'Manual positioning of colorbars - Right Out';
stat.issues = [933 937];
axLoc = 'out';
figPos = [1 , 1, 11 ,10];
axPos(1,:) = [1 , 1, 8 , 3];
axPos(2,:) = [1 , 5, 8 , 3];
cbPos = [9.5, 1, 0.5, 7];
colorbarManualLocationHelper_(figPos, axPos, cbPos, axLoc);
end
function [stat] = colorbarManualLocationRightIn()
stat.description = 'Manual positioning of colorbars - Right In';
stat.issues = [933 937];
axLoc = 'in';
figPos = [ 1 , 1, 11 ,10];
axPos(1,:) = [ 1 , 1, 8 , 3];
axPos(2,:) = [ 1 , 5, 8 , 3];
cbPos = [10.5, 1, 0.5, 7];
colorbarManualLocationHelper_(figPos, axPos, cbPos, axLoc);
end
function [stat] = colorbarManualLocationLeftOut()
stat.description = 'Manual positioning of colorbars - Left Out';
stat.issues = [933 937];
axLoc = 'out';
figPos = [1 , 1, 11 , 10];
axPos(1,:) = [2.5, 1, 8 , 3];
axPos(2,:) = [2.5, 5, 8 , 3];
cbPos = [1.5, 1, 0.5, 7];
colorbarManualLocationHelper_(figPos, axPos, cbPos, axLoc);
end
function [stat] = colorbarManualLocationLeftIn()
stat.description = 'Manual positioning of colorbars - Left In';
stat.issues = [933 937];
axLoc = 'in';
figPos = [1 , 1, 11 , 10];
axPos(1,:) = [2.5, 1, 8 , 3];
axPos(2,:) = [2.5, 5, 8 , 3];
cbPos = [0.5, 1, 0.5, 7];
colorbarManualLocationHelper_(figPos, axPos, cbPos, axLoc);
end
function colorbarManualLocationHelper_(figPos, axPos, cbPos, axLoc)
% this is a helper function, not a test case
set(gcf, 'Units','centimeters','Position', figPos);
hAx(1) = axes('Units', 'centimeters', 'Position', axPos(1,:));
imagesc([1,2,3], [4,5,6], magic(3)/9, [0,1]);
hAx(2) = axes('Units', 'centimeters', 'Position', axPos(2,:));
imagesc([1,2,3], [4,5,6], magic(3)/9, [0,1]);
hCb = colorbar('Units', 'centimeters', 'Position', cbPos);
try
% only in HG2
%TODO: check if there are HG1 / Octave counterparts for this property
set(hCb, 'AxisLocation', axLoc);
end
labelProperty = {'Label', 'YLabel'}; %YLabel as fallback for
idxLabel = find(cellfun(@(p) isprop(hCb, p), labelProperty), 1);
if ~isempty(idxLabel)
hLabel = get(hCb, labelProperty{idxLabel});
set(hLabel, 'String', ['AxisLocation = ' axLoc]);
end
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
testPatches.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/suites/testPatches.m
| 3,826 |
utf_8
|
234dc3a01511762ef5f641ff068318c3
|
function status = testPatches(k)
% TESTPATCHES Test suite for patches
%
% See also: ACID, matlab2tikz_acidtest
testfunction_handles = {
@patch01;
@patch02;
@patch03;
@patch04;
@patch05;
@patch06;
@patch07;
@patch08;
};
numFunctions = length( testfunction_handles );
if nargin < 1 || isempty(k) || k <= 0
status = testfunction_handles;
return; % This is used for querying numFunctions.
elseif (k<=numFunctions)
status = testfunction_handles{k}();
status.function = func2str(testfunction_handles{k});
else
error('patchTests:outOfBounds', ...
'Out of bounds (number of testfunctions=%d)', numFunctions);
end
end
% =========================================================================
function p = patch00()
% DO NOT INCLUDE IN ACID LIST
% Base patch plot for following tests
xdata = [2 2 0 2 5; 2 8 2 4 5; 8 8 2 4 8];
ydata = [4 4 4 2 0; 8 4 6 2 2; 4 0 4 0 0];
zdata = ones(3,5)*2;
p = patch(xdata,ydata,zdata);
end
% =========================================================================
function stat = patch01()
stat.description = 'Set face color red';
p = patch00();
set(p,'FaceColor','r')
end
% =========================================================================
function stat = patch02()
stat.description = 'Flat face colors scaled in clim [0,40]';
p = patch00();
set(gca,'CLim',[0 40])
cdata = [15 30 25 2 60];
set(p,'FaceColor','flat','CData',cdata,'CDataMapping','scaled')
end
% =========================================================================
function stat = patch03()
stat.description = 'Flat face colors direct in clim [0,40]';
p = patch00();
set(gca,'CLim',[0 40])
cdata = [15 30 25 2 60];
set(p,'FaceColor','flat','CData',cdata,'CDataMapping','direct')
end
% =========================================================================
function stat = patch04()
stat.description = 'Flat face colors with 3D (truecolor) CData';
p = patch00();
cdata(:,:,1) = [0 0 1 0 0.8];
cdata(:,:,2) = [0 0 0 0 0.8];
cdata(:,:,3) = [1 1 1 0 0.8];
set(p,'FaceColor','flat','CData',cdata)
end
% =========================================================================
function stat = patch05()
stat.description = 'Flat face color, scaled edge colors in clim [0,40]';
p = patch00();
set(gca,'CLim',[0 40])
cdata = [15 30 25 2 60; 12 23 40 13 26; 24 8 1 65 42];
set(p,'FaceColor','flat','CData',cdata,'EdgeColor','flat','LineWidth',5,'CDataMapping','scaled')
end
% =========================================================================
function stat = patch06()
stat.description = 'Flat face color, direct edge colors in clim [0,40]';
p = patch00();
set(gca,'CLim',[0 40])
cdata = [15 30 25 2 60; 12 23 40 13 26; 24 8 1 65 42];
set(p,'FaceColor','flat','CData',cdata,'EdgeColor','flat','LineWidth',5,'CDataMapping','direct')
end
% =========================================================================
function stat = patch07()
stat.description = 'Flat face color with 3D CData and interp edge colors';
p = patch00();
cdata(:,:,1) = [0 0 1 0 0.8;
0 0 1 0.2 0.6;
0 1 0 0.4 1];
cdata(:,:,2) = [0 0 0 0 0.8;
1 1 1 0.2 0.6;
1 0 0 0.4 0];
cdata(:,:,3) = [1 1 1 0 0.8;
0 1 0 0.2 0.6;
1 0 1 0.4 0];
set(p,'FaceColor','flat','CData',cdata,'EdgeColor','interp','LineWidth',5)
end
% =========================================================================
function stat = patch08()
stat.description = 'Interp face colors, flat edges, scaled CData in clims [0,40]';
p = patch00();
set(gca,'CLim',[0 40])
cdata = [15 30 25 2 60; 12 23 40 13 26; 24 8 1 65 42];
set(p,'FaceColor','interp','CData',cdata,'EdgeColor','flat','LineWidth',5,'CDataMapping','scaled')
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
testSurfshader.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/suites/testSurfshader.m
| 3,244 |
utf_8
|
a1459ba222d417e599f3306930e71ccf
|
function status = testSurfshader(k)
% TESTSURFSHADER Test suite for Surf/mesh shaders (coloring)
%
% See also: ACID, matlab2tikz_acidtest
testfunction_handles = {
@surfShader1;
@surfShader2;
@surfShader3;
@surfShader4;
@surfShader5;
@surfNoShader;
@surfNoPlot;
@surfMeshInterp;
@surfMeshRGB;
};
numFunctions = length( testfunction_handles );
if nargin < 1 || isempty(k) || k <= 0
status = testfunction_handles;
return; % This is used for querying numFunctions.
elseif (k<=numFunctions)
status = testfunction_handles{k}();
status.function = func2str(testfunction_handles{k});
else
error('patchTests:outOfBounds', ...
'Out of bounds (number of testfunctions=%d)', numFunctions);
end
end
% =========================================================================
function [stat] = surfShader1()
stat.description = 'shader=flat/(flat mean) | Fc: flat | Ec: none';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','flat','EdgeColor','none')
end
% =========================================================================
function [stat] = surfShader2()
stat.description = 'shader=interp | Fc: interp | Ec: none';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','interp','EdgeColor','none')
end
% =========================================================================
function [stat] = surfShader3()
stat.description = 'shader=faceted | Fc: flat | Ec: RGB';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','flat','EdgeColor','green')
end
% =========================================================================
function [stat] = surfShader4()
stat.description = 'shader=faceted | Fc: RGB | Ec: interp';
if isMATLAB('<', [8,4]); %R2014a and older
warning('m2t:ACID:surfShader4',...
'The MATLAB EPS export may behave strangely for this case');
end
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','blue','EdgeColor','interp')
end
% =========================================================================
function [stat] = surfShader5()
stat.description = 'shader=faceted interp | Fc: interp | Ec: flat';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','interp','EdgeColor','flat')
end
% =========================================================================
function [stat] = surfNoShader()
stat.description = 'no shader | Fc: RGB | Ec: RGB';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','blue','EdgeColor','yellow')
end
% =========================================================================
function [stat] = surfNoPlot()
stat.description = 'no plot | Fc: none | Ec: none';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','none','EdgeColor','none')
end
% =========================================================================
function [stat] = surfMeshInterp()
stat.description = 'mesh | Fc: none | Ec: interp';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','none','EdgeColor','interp')
end
% =========================================================================
function [stat] = surfMeshRGB()
stat.description = 'mesh | Fc: none | Ec: RGB';
[X,Y,Z] = peaks(5);
surf(X,Y,Z,'FaceColor','none','EdgeColor','green')
end
% =========================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
isVersionBelow.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/suites/private/isVersionBelow.m
| 1,396 |
utf_8
|
e27c354a6fd26c00f6b9c239ad50bbd2
|
function isBelow = isVersionBelow(versionA, versionB)
% Checks if versionA is smaller than versionB
vA = versionArray(versionA);
vB = versionArray(versionB);
n = min(length(vA), length(vB));
deltaAB = vA(1:n) - vB(1:n);
difference = find(deltaAB, 1, 'first');
if isempty(difference)
isBelow = false; % equal versions
else
isBelow = (deltaAB(difference) < 0);
end
end
% ==============================================================================
function arr = versionArray(str)
% Converts a version string to an array.
if ischar(str)
% Translate version string from '2.62.8.1' to [2; 62; 8; 1].
switch getEnvironment
case 'MATLAB'
split = regexp(str, '\.', 'split'); % compatibility MATLAB < R2013a
case 'Octave'
split = strsplit(str, '.');
otherwise
errorUnknownEnvironment();
end
arr = str2num(char(split)); %#ok
else
arr = str;
end
arr = arr(:)';
end
% ==============================================================================
function errorUnknownEnvironment()
error('matlab2tikz:unknownEnvironment',...
'Unknown environment "%s". Need MATLAB(R) or Octave.', getEnvironment);
end
% ==============================================================================
|
github
|
ga96jul/Bachelarbeit-master
|
initializeGlobalState.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/initializeGlobalState.m
| 4,128 |
utf_8
|
5cdca5d96a05a8efc1abc41f1d245972
|
function [orig] = initializeGlobalState()
% Initialize global state. Set working directory and various properties of
% the graphical root to ensure reliable output of the ACID testsuite.
% See #542 and #552
%
% 1. Working directory
% 2. Bring get(0,'Default') in line with get(0,'Factory')
% 3. Set specific properties, required by matlab2tikz
fprintf('Initialize global state...\n');
orig = struct();
%--- Extract user defined default properties and set factory state
default = get(0,'Default');
factory = get(0,'Factory');
f = fieldnames(default); % fields of user's default state
for i = 1:length(f)
factory_property_name = strrep(f{i},'default','factory');
factory_property_value = factory.(factory_property_name);
orig.(f{i}).val = ...
swapPropertyState(0, f{i}, factory_property_value);
end
%--- Define desired global state properties
% defaultAxesColorOrder: on HG1 'default' and 'factory' differ and
% HG1 differs from HG2. Consequently use HG2 colors (the new standard).
new.defaultAxesColorOrder.val = [0.000 0.447 0.741; ...
0.850 0.325 0.098; ...
0.929 0.694 0.125; ...
0.494 0.184 0.556; ...
0.466 0.674 0.188; ...
0.301 0.745 0.933; ...
0.635 0.0780 0.184];
new.defaultAxesColorOrder.ignore= false;
% defaultFigurePosition: width and height influence cleanfigure() and
% the number/location of axis ticks
new.defaultFigurePosition.val = [300,200,560,420];
new.defaultFigurePosition.ignore= false;
% ScreenPixelsPerInch: TODO: determine, if necessary
% (probably needed for new line simplification algorithm)
% not possible in octave
new.ScreenPixelsPerInch.val = 96;
new.ScreenPixelsPerInch.ignore = strcmpi(getEnvironment,'octave');
% MATLAB's factory values differ from their default values of a clean
% MATLAB installation (observed on R2014a, Linux)
new.defaultAxesColor.val = [1 1 1];
new.defaultAxesColor.ignore = false;
new.defaultLineColor.val = [0 0 0];
new.defaultLineColor.ignore = false;
new.defaultTextColor.val = [0 0 0];
new.defaultTextColor.ignore = false;
new.defaultAxesXColor.val = [0 0 0];
new.defaultAxesXColor.ignore = false;
new.defaultAxesYColor.val = [0 0 0];
new.defaultAxesYColor.ignore = false;
new.defaultAxesZColor.val = [0 0 0];
new.defaultAxesZColor.ignore = false;
new.defaultFigureColor.val = [0.8 0.8 0.8];
new.defaultFigureColor.ignore = false;
new.defaultPatchEdgeColor.val = [0 0 0];
new.defaultPatchEdgeColor.ignore = false;
new.defaultPatchFaceColor.val = [0 0 0];
new.defaultPatchFaceColor.ignore = false;
new.defaultFigurePaperType.val = 'A4';
new.defaultFigurePaperType.ignore = false;
new.defaultFigurePaperSize.val = [20.9840 29.6774];
new.defaultFigurePaperSize.ignore = false;
new.defaultFigurePaperUnits.val = 'centimeters';
new.defaultFigurePaperUnits.ignore = false;
%--- Extract relevant properties and set desired state
f = fieldnames(new); % fields of new state
for i = 1:length(f)
% ignore property on specified environments
if ~new.(f{i}).ignore
val = swapPropertyState(0, f{i}, new.(f{i}).val);
% store original value only, if not set by user's defaults
if ~isfield(orig,f{i})
orig.(f{i}).val = val;
end
end
end
end
% =========================================================================
function old = swapPropertyState(h, property, new)
% read current property of graphical object
% set new value, if not empty
if nargin < 3, new = []; end
old = get(h, property);
if ~isempty(new)
set(h, property, new);
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
StreamMaker.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/StreamMaker.m
| 2,389 |
utf_8
|
8241d9d3fec9eb06a1e4c5437191e3b9
|
function SM = StreamMaker()
% StreamMaker (Factory for fie/input/output Streams)
%
% A StreamMaker can make Stream PseudoObjects based on either
% an "fid" or "filename" (and extra arguments for `fopen`).
% The StreamMaker also contains a method `isStream` to validate whether
% the value passed is a valid stream specifier.
%
% Usage
%
% SM = StreamMaker;
%
% Stream = SM.make(fid)
% Stream = SM.make(filename, ...)
%
% This returns a PseudoObject Stream with the following properties:
% - name: (file) name of the stream
% - fid: handle (fid) of the stream
%
% and methods:
% - print: prints to the stream, i.e. fprintf
% - close: closes the stream, i.e. fclose
%
% It may also contain a field to automatically close the Stream when it goes
% out of scope.
%
SM = PseudoObject('StreamMaker', ...
'isStream', @isStream, ...
'make', @constructStream);
end
function PseudoObj = PseudoObject(T, varargin)
% construct a Pseudo-Object with type T (no other fields yet)
PseudoObj = struct('Type', T, varargin{:});
end
function bool = isStream(value)
bool = ischar(value) || ismember(value, [1,2,fopen('all')]);
%TODO: allow others kinds of streams
% Stream -> clipboard (write on close)
% Stream -> string variable
% e.g. a quick-and-dirty way would be to write the file to `tempname`
% putting a flag to read that file back upon completion.
end
function Stream = constructStream(streamSpecifier, varargin)
% this is the actual constructor of a stream
if ~isStream(streamSpecifier)
error('StreamMaker:NotAStream', 'Invalid stream specifier "%s"', ...
streamSpecifier);
end
Stream = PseudoObject('Stream');
closeAfterUse = false;
if ischar(streamSpecifier)
Stream.name = streamSpecifier;
Stream.fid = fopen(Stream.name, varargin{:});
closeAfterUse = true;
elseif isnumeric(streamSpecifier)
Stream.fid = streamSpecifier;
Stream.name = fopen(Stream.fid);
end
if Stream.fid == -1
error('Stream:InvalidStream', ...
'Unable to create stream "%s"!', streamSpecifier);
end
Stream.print = @(varargin) fprintf(Stream.fid, varargin{:});
Stream.close = @() fclose(Stream.fid);
if closeAfterUse
Stream.closeAfterUse = onCleanup(Stream.close);
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
execute_save_stage.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/execute_save_stage.m
| 2,508 |
utf_8
|
ae0f150d3878e9f1b42ad84004424320
|
function [status] = execute_save_stage(status, ipp)
% save stage: saves the figure to EPS/PDF depending on env
testNumber = status.index;
basepath = fullfile(ipp.Results.output,'data','reference');
reference_eps = fullfile(basepath, sprintf('test%d-reference.eps', testNumber));
reference_pdf = fullfile(basepath, sprintf('test%d-reference.pdf', testNumber));
% the reference below is for inclusion in LaTeX! Use UNIX conventions!
reference_fig = sprintf('data/reference/test%d-reference', testNumber);
% Save reference output as PDF
try
switch getEnvironment
case 'MATLAB'
% MATLAB does not generate properly cropped PDF files.
% So, we generate EPS files that are converted later on.
print(gcf, '-depsc2', reference_eps);
fixLineEndingsInWindows(reference_eps);
case 'Octave'
% In Octave, figures are properly cropped when using print().
print(reference_pdf, '-dpdf', '-S415,311', '-r150');
pause(1.0)
otherwise
error('matlab2tikz:UnknownEnvironment', ...
'Unknown environment. Need MATLAB(R) or GNU Octave.')
end
catch %#ok
e = lasterror('reset'); %#ok
[status.saveStage] = errorHandler(e);
end
status.saveStage.epsFile = reference_eps;
status.saveStage.pdfFile = reference_pdf;
status.saveStage.texReference = reference_fig;
end
% ==============================================================================
function fixLineEndingsInWindows(filename)
% On R2014b Win, line endings in .eps are Unix style (LF) instead of Windows
% style (CR+LF). This causes problems in the MikTeX `epstopdf` for some files
% as dicussed in:
% * https://github.com/matlab2tikz/matlab2tikz/issues/370
% * http://tex.stackexchange.com/questions/208179
if ispc
fid = fopen(filename,'r+');
finally_fclose_fid = onCleanup(@() fclose(fid));
testline = fgets(fid);
CRLF = sprintf('\r\n');
endOfLine = testline(end-1:end);
if ~strcmpi(endOfLine, CRLF)
endOfLine = testline(end); % probably an LF
% Rewind, read the whole
fseek(fid,0,'bof');
str = fread(fid,'*char')';
% Replace, overwrite and close
str = strrep(str, endOfLine, CRLF);
fseek(fid,0,'bof');
fprintf(fid,'%s',str);
end
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
testMatlab2tikz.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/testMatlab2tikz.m
| 5,167 |
utf_8
|
55b92776e6ddb66aadbb483b8e0a3949
|
function [status, parameters] = testMatlab2tikz(varargin)
%TESTMATLAB2TIKZ unit test driver for matlab2tikz
%
% This function should NOT be called directly by the user (or even developer).
% If you are a developer, please use some of the following functions instead:
% * `testHeadless`
% * `testGraphical`
%
% The following arguments are supported, also for the functions above.
%
% TESTMATLAB2TIKZ('testFunctionIndices', INDICES, ...) or
% TESTMATLAB2TIKZ(INDICES, ...) runs the test only for the specified
% indices. When empty, all tests are run. (Default: []).
%
% TESTMATLAB2TIKZ('extraOptions', {'name',value, ...}, ...)
% passes the cell array of options to MATLAB2TIKZ. Default: {}
%
% TESTMATLAB2TIKZ('figureVisible', LOGICAL, ...)
% plots the figure visibly during the test process. Default: false
%
% TESTMATLAB2TIKZ('testsuite', FUNCTION_HANDLE, ...)
% Determines which test suite is to be run. Default: @ACID
% A test suite is a function that takes a single integer argument, which:
% when 0: returns a cell array containing the N function handles to the tests
% when >=1 and <=N: runs the appropriate test function
% when >N: throws an error
%
% TESTMATLAB2TIKZ('output', DIRECTORY, ...)
% Sets the output directory where the output files are places.
% The default directory is $M2TROOT/test/output/current
%
% See also matlab2tikz, ACID
% In which environment are we?
env = getEnvironment();
% -----------------------------------------------------------------------
ipp = m2tInputParser;
ipp = ipp.addOptional(ipp, 'testFunctionIndices', [], @isfloat);
ipp = ipp.addParamValue(ipp, 'extraOptions', {}, @iscell);
ipp = ipp.addParamValue(ipp, 'figureVisible', false, @islogical);
ipp = ipp.addParamValue(ipp, 'actionsToExecute', @(varargin) varargin{1}, @isFunction);
ipp = ipp.addParamValue(ipp, 'testsuite', @ACID, @isFunction );
ipp = ipp.addParamValue(ipp, 'output', m2troot('test','output','current'), @ischar);
ipp = ipp.parse(ipp, varargin{:});
ipp = sanitizeInputs(ipp);
parameters = ipp.Results;
% -----------------------------------------------------------------------
if strcmpi(env, 'Octave')
if ~ipp.Results.figureVisible
% Use the gnuplot backend to work around an fltk bug, see
% <http://savannah.gnu.org/bugs/?43429>.
graphics_toolkit gnuplot
end
if ispc
% Prevent three digit exponent on Windows Octave
% See https://github.com/matlab2tikz/matlab2tikz/pull/602
setenv ('PRINTF_EXPONENT_DIGITS', '2')
end
end
% copy output template into output directory
if ~exist(ipp.Results.output,'dir')
mkdir(ipp.Results.output);
end
template = m2troot('test','template');
copyfile(fullfile(template,'*'), ipp.Results.output);
% start overall timing
elapsedTimeOverall = tic;
status = runIndicatedTests(ipp);
% print out overall timing
elapsedTimeOverall = toc(elapsedTimeOverall);
stdout = 1;
fprintf(stdout, 'overall time: %4.2fs\n\n', elapsedTimeOverall);
end
% INPUT VALIDATION =============================================================
function bool = isFunction(f)
bool = isa(f,'function_handle');
end
function ipp = sanitizeInputs(ipp)
% sanitize all input arguments
ipp = sanitizeFunctionIndices(ipp);
ipp = sanitizeFigureVisible(ipp);
end
function ipp = sanitizeFunctionIndices(ipp)
% sanitize the passed function indices to the range of the test suite
% query the number of test functions
testsuite = ipp.Results.testsuite;
n = length(testsuite(0));
if ~isempty(ipp.Results.testFunctionIndices)
indices = ipp.Results.testFunctionIndices;
% kick out the illegal stuff
I = find(indices>=1 & indices<=n);
indices = indices(I); %#ok
else
indices = 1:n;
end
ipp.Results.testFunctionIndices = indices;
end
function ipp = sanitizeFigureVisible(ipp)
% sanitizes the figure visible option from boolean to ON/OFF
if ipp.Results.figureVisible
ipp.Results.figureVisible = 'on';
else
ipp.Results.figureVisible = 'off';
end
end
% TEST RUNNER ==================================================================
function status = runIndicatedTests(ipp)
% run all indicated tests in the test suite
% cell array to accomodate different structure
indices = ipp.Results.testFunctionIndices;
testsuite = ipp.Results.testsuite;
testsuiteName = func2str(testsuite);
stdout = 1;
status = cell(length(indices), 1);
for k = 1:length(indices)
testNumber = indices(k);
fprintf(stdout, 'Executing %s test no. %d...\n', testsuiteName, indices(k));
status{k} = emptyStatus(testsuite, testNumber);
elapsedTime = tic;
status{k} = feval(ipp.Results.actionsToExecute, status{k}, ipp);
elapsedTime = toc(elapsedTime);
status{k}.elapsedTime = elapsedTime;
fprintf(stdout, '%s ', status{k}.function);
if status{k}.skip
fprintf(stdout, 'skipped (%4.2fs).\n\n', elapsedTime);
else
fprintf(stdout, 'done (%4.2fs).\n\n', elapsedTime);
end
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
execute_hash_stage.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/execute_hash_stage.m
| 1,223 |
utf_8
|
6184f50e662c3c17703266f7a350ea68
|
function [status] = execute_hash_stage(status, ipp)
% test stage: check recorded hash checksum
calculated = '';
expected = '';
try
expected = getReferenceHash(status, ipp);
calculated = calculateMD5Hash(status.tikzStage.texFile);
% do the actual check
if ~strcmpi(expected, calculated)
% throw an error to signal the testing framework
error('testMatlab2tikz:HashMismatch', ...
'The hash "%s" does not match the reference hash "%s"', ...
calculated, expected);
end
catch %#ok
e = lasterror('reset'); %#ok
[status.hashStage] = errorHandler(e);
end
status.hashStage.expected = expected;
status.hashStage.found = calculated;
end
% ==============================================================================
function hash = getReferenceHash(status, ipp)
% retrieves a reference hash from a hash table
% WARNING: do not make `hashTable` persistent, since this is slower
hashTable = loadHashTable(ipp.Results.testsuite);
if isfield(hashTable.contents, status.function)
hash = hashTable.contents.(status.function);
else
hash = '';
end
end
|
github
|
ga96jul/Bachelarbeit-master
|
errorHandler.m
|
.m
|
Bachelarbeit-master/Bachelorarbeit/05_Libraries/matlab2tikz-matlab2tikz-816f875/test/private/errorHandler.m
| 1,593 |
utf_8
|
192f9bd9629a58a55e84e47ed41af93c
|
function [stage, errorHasOccurred] = errorHandler(e)
% common error handler code: save and print to console
errorHasOccurred = true;
stage = emptyStage();
stage.message = format_error_message(e);
stage.error = errorHasOccurred;
disp_error_message(stage.message);
end
% ==============================================================================
function msg = format_error_message(e)
msg = '';
if ~isempty(e.message)
msg = sprintf('%serror: %s\n', msg, e.message);
end
if ~isempty(e.identifier)
if strfind(lower(e.identifier),'testmatlab2tikz:')
% When "errors" occur in the test framework, i.e. a hash mismatch
% or no hash provided, there is no need to be very verbose.
% So we don't return the msgid and the stack trace in those cases!
return % only return the message
end
msg = sprintf('%serror: %s\n', msg, e.identifier);
end
if ~isempty(e.stack)
msg = sprintf('%serror: called from:\n', msg);
for ee = e.stack(:)'
msg = sprintf('%serror: %s at line %d, in function %s\n', ...
msg, ee.file, ee.line, ee.name);
end
end
end
% ==============================================================================
function disp_error_message(msg)
stderr = 2;
% The error message should not contain any more escape sequences and
% hence can be output literally to stderr.
fprintf(stderr, '%s', msg);
end
% ==============================================================================
|
github
|
baolinhu/face_compare-master
|
urlreadpost.m
|
.m
|
face_compare-master/face_com_face++_matlab/urlreadpost.m
| 4,124 |
utf_8
|
415c4cf82008395df7350567049758f0
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output,status] = urlreadpost(urlChar,params)
%URLREADPOST Returns the contents of a URL POST method as a string.
% S = URLREADPOST('URL',PARAMS) passes information to the server as
% a POST request. PARAMS is a cell array of param/value pairs.
%
% Unlike stock urlread, this version uses the multipart/form-data
% encoding, and can thus post file content. File data is
% encoded as a value element of numerical type (e.g. uint8)
% in PARAMS. For example:
%
% f = fopen('music.mp3');
% d = fread(f,Inf,'*uint8'); % Read in byte stream of MP3 file
% fclose(f);
% str = urlreadpost('http://developer.echonest.com/api/upload', ...
% {'file',dd,'version','3','api_key','API-KEY','wait','Y'});
%
% ... will upload the mp3 file to the Echo Nest Analyze service.
%
% Based on TMW's URLREAD. Note that unlike URLREAD, there is no
% METHOD argument
% 2010-04-07 Dan Ellis [email protected]
% This function requires Java.
if ~usejava('jvm')
error('MATLAB:urlreadpost:NoJvm','URLREADPOST requires Java.');
end
import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;
% Be sure the proxy settings are set.
com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings
% Check number of inputs and outputs.
error(nargchk(2,2,nargin))
error(nargoutchk(0,2,nargout))
if ~ischar(urlChar)
error('MATLAB:urlreadpost:InvalidInput','The first input, the URL, must be a character array.');
end
% Do we want to throw errors or catch them?
if nargout == 2
catchErrors = true;
else
catchErrors = false;
end
% Set default outputs.
output = '';
status = 0;
% Create a urlConnection.
[urlConnection,errorid,errormsg] = urlreadwrite(mfilename,urlChar);
if isempty(urlConnection)
if catchErrors, return
else error(errorid,errormsg);
end
end
% POST method. Write param/values to server.
% Modified for multipart/form-data 2010-04-06 [email protected]
% try
urlConnection.setDoOutput(true);
boundary = '***********************';
urlConnection.setRequestProperty( ...
'Content-Type',['multipart/form-data; boundary=',boundary]);
printStream = java.io.PrintStream(urlConnection.getOutputStream);
% also create a binary stream
dataOutputStream = java.io.DataOutputStream(urlConnection.getOutputStream);
eol = [char(13),char(10)];
for i=1:2:length(params)
printStream.print(['--',boundary,eol]);
printStream.print(['Content-Disposition: form-data; name="',params{i},'"']);
if ~ischar(params{i+1})
% binary data is uploaded as an octet stream
% Echo Nest API demands a filename in this case
printStream.print(['; filename="dummy"',eol]);
printStream.print(['Content-Type: application/octet-stream',eol]);
printStream.print([eol]);
dataOutputStream.write(params{i+1},0,length(params{i+1}));
printStream.print([eol]);
else
printStream.print([eol]);
printStream.print([eol]);
printStream.print([params{i+1},eol]);
end
end
printStream.print(['--',boundary,'--',eol]);
printStream.close;
% catch
% if catchErrors, return
% else error('MATLAB:urlread:ConnectionFailed','Could not POST to URL.');
% end
% end
% Read the data from the connection.
try
inputStream = urlConnection.getInputStream;
byteArrayOutputStream = java.io.ByteArrayOutputStream;
% This StreamCopier is unsupported and may change at any time.
isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
isc.copyStream(inputStream,byteArrayOutputStream);
inputStream.close;
byteArrayOutputStream.close;
output = native2unicode(typecast(byteArrayOutputStream.toByteArray','uint8'),'UTF-8');
catch
if catchErrors, return
else error('MATLAB:urlreadpost:ConnectionFailed','Error downloading URL. Your network connection may be down or your proxy settings improperly configured.');
end
end
status = 1;
|
github
|
baolinhu/face_compare-master
|
parse_json.m
|
.m
|
face_compare-master/face_com_face++_matlab/parse_json.m
| 5,591 |
utf_8
|
511272119247075d3fa284c56d18e945
|
function [data json] = parse_json(json)
% [DATA JSON] = PARSE_JSON(json)
% This function parses a JSON string and returns a cell array with the
% parsed data. JSON objects are converted to structures and JSON arrays are
% converted to cell arrays.
%
% Example:
% google_search = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=matlab';
% matlab_results = parse_json(urlread(google_search));
% disp(matlab_results{1}.responseData.results{1}.titleNoFormatting)
% disp(matlab_results{1}.responseData.results{1}.visibleUrl)
data = cell(0,1);
while ~isempty(json)
[value json] = parse_value(json);
data{end+1} = value; %#ok<AGROW>
end
end
function [value json] = parse_value(json)
value = [];
if ~isempty(json)
id = json(1);
json(1) = [];
json = strtrim(json);
switch lower(id)
case '"'
[value json] = parse_string(json);
case '{'
[value json] = parse_object(json);
case '['
[value json] = parse_array(json);
case 't'
value = true;
if (length(json) >= 3)
json(1:3) = [];
else
ME = MException('json:parse_value',['Invalid TRUE identifier: ' id json]);
ME.throw;
end
case 'f'
value = false;
if (length(json) >= 4)
json(1:4) = [];
else
ME = MException('json:parse_value',['Invalid FALSE identifier: ' id json]);
ME.throw;
end
case 'n'
value = [];
if (length(json) >= 3)
json(1:3) = [];
else
ME = MException('json:parse_value',['Invalid NULL identifier: ' id json]);
ME.throw;
end
otherwise
[value json] = parse_number([id json]); % Need to put the id back on the string
end
end
end
function [data json] = parse_array(json)
data = cell(0,1);
while ~isempty(json)
if strcmp(json(1),']') % Check if the array is closed
json(1) = [];
return
end
[value json] = parse_value(json);
if isempty(value)
ME = MException('json:parse_array',['Parsed an empty value: ' json]);
ME.throw;
end
data{end+1} = value; %#ok<AGROW>
while ~isempty(json) && ~isempty(regexp(json(1),'[\s,]','once'))
json(1) = [];
end
end
end
function [data json] = parse_object(json)
data = [];
while ~isempty(json)
id = json(1);
json(1) = [];
switch id
case '"' % Start a name/value pair
[name value remaining_json] = parse_name_value(json);
if isempty(name)
ME = MException('json:parse_object',['Can not have an empty name: ' json]);
ME.throw;
end
data.(name) = value;
json = remaining_json;
case '}' % End of object, so exit the function
return
otherwise % Ignore other characters
end
end
end
function [name value json] = parse_name_value(json)
name = [];
value = [];
if ~isempty(json)
[name json] = parse_string(json);
% Skip spaces and the : separator
while ~isempty(json) && ~isempty(regexp(json(1),'[\s:]','once'))
json(1) = [];
end
[value json] = parse_value(json);
end
end
function [string json] = parse_string(json)
string = [];
while ~isempty(json)
letter = json(1);
json(1) = [];
switch lower(letter)
case '\' % Deal with escaped characters
if ~isempty(json)
code = json(1);
json(1) = [];
switch lower(code)
case '"'
new_char = '"';
case '\'
new_char = '\';
case '/'
new_char = '/';
case {'b' 'f' 'n' 'r' 't'}
new_char = sprintf('\%c',code);
case 'u'
if length(json) >= 4
new_char = sprintf('\\u%s',json(1:4));
json(1:4) = [];
end
otherwise
new_char = [];
end
end
case '"' % Done with the string
return
otherwise
new_char = letter;
end
% Append the new character
string = [string new_char]; %#ok<AGROW>
end
end
function [num json] = parse_number(json)
num = [];
if ~isempty(json)
% Validate the floating point number using a regular expression
[s e] = regexp(json,'^[\w]?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?[\w]?','once');
if ~isempty(s)
num_str = json(s:e);
json(s:e) = [];
num = str2double(strtrim(num_str));
end
end
end
|
github
|
johnR46/artificial-neural-network-Basic-master
|
LED_1.m
|
.m
|
artificial-neural-network-Basic-master/LED.M/LED_1.m
| 2,551 |
utf_8
|
62dc1b76560e52837a84d5c7f0a32727
|
clear all %clear all variables
close all %close all figure
clc %clear screen
NUMBER_ARGS = 5
int8 numtrain;
uint8 seed;
char outputfile[100];
int8 percentnoise;
int8 noisy[7]; % /* Contains boolean values (attribute noise) */
int8 instance[10][7]; %/* Original 10 instances */
int8 n;n=0;
function void = main(argc, argv)
int8 argc;
char *argv[];
createworld();
if(argc ~= NUMBER_ARGS)
printf("Arguments: numtrain seed outputfile noise.\n");
printf(" numtrain is the number of training instances requested.\n");
printf(" seed is a integer seed for the random number generator.\n");
printf(" outputfile: output file name for the generated instances.\n");
printf(" noise is the percent probability of noise per attribute.\n");
printf(" (usually set to 10%...and reported by the program)\n");
else
numtrain = str2num(argv(1));
seed = str2num(argv(2));
strcpy(outputfile,argv(3));
percentnoise = str2num(argv(4));
createworld();
end
end
function void = createworld()
%prepare to save result in file
fid = fopen('resultLED.txt','w');
int8 select_noisy_indexes();
int8 noisy_index();
int8 count;
int8 selected;
int8 noisy_instance[7];
double actual;
srandom(seed);
instance=[ 1,1,1,0,1,1,1 ; 0,0,1,0,0,1,0
1,0,1,1,1,0,1 ; 1,0,1,1,0,1,1
0,1,1,1,0,1,0 ; 1,1,0,1,0,1,1
1,1,0,1,1,1,1 ; 1,0,1,0,0,1,0
1,1,1,1,1,1,1 ; 1,1,1,1,0,1,1 ]
fid = fopen(outputfile,"w");
for count = 0:numtrain
select_noisy_indexes();
selected = rem(random(),10);
for y = 0:7
noisy_instance(y) = instance(selected),(y);
if (noisy(y))
noisy_instance(y) = ~noisy_instance(y);
end
end
fprintf(fid,"%d,%d,%d,%d,%d,%d,%d,%d\n",noisy_instance(0),noisy_instance(1),noisy_instance(2),noisy_instance(3),noisy_instance(4),noisy_instance(5),noisy_instance(6),selected);
end
actual = 100.0 * n / (7*numtrain);
printf("Percent Noise: Requested %d, Actual %f\n",percentnoise,actual);
fclose(fid);
end
function int = select_noisy_indexes()
int8 i;
double actual;
for y = 0:7
noisy(y) = 0;
if( ( 1 + (rem(random(),100))) <= percentnoise)
noisy(y) = 1;
n = n+1;
end
end
end
|
github
|
johnR46/artificial-neural-network-Basic-master
|
LED_2.m
|
.m
|
artificial-neural-network-Basic-master/LED.M/LED_2.m
| 2,893 |
utf_8
|
9b7b4b134e9e15d474f54cca73a6ab91
|
clear all %clear all variables
close all %close all figure
clc %clear screen
NUMBER_ARGS = 5
%/*==== Inputs ====*/
int8 numtrain; % /*==== Input #1 ====*/
uint8 seed; % /*==== Input #2 ====*/
char outputfile[100]; % /*==== Input #3 ====*/
int8 percentnoise;
%/*==== Other global values ====*/
int8 noisy[7]; %/* Contains boolean values (attribute noise) */
int8 instance[10][7]; %/* Original 10 instances */
int8 n;n=0;
int8 num_irrelevant_attributes;num_irrelevant_attributes = 17;
function void = main (argc, argv)
int argc;
char *argv[];
if argc ~= NUMBER_ARGS
printf("Arguments: numtrain seed outputfile noise.\n");
printf(" numtrain is the number of training instances requested.\n");
printf(" seed is a integer seed for the random number generator.\n");
printf(" outputfile: output file name for the generated instances.\n");
printf(" noise is the percent probability of noise per attribute.\n");
printf(" (usually set to 10%...and reported by the program)\n");
else
numtrain = str2num(argv(1));
seed = str2num(argv(2));
strcpy(outputfile,argv(3));
percentnoise = str2num(argv(4));
createworld();
end
end
function void = createworld()
%prepare to save result in file
fid = fopen('resultLED2.txt','w');
int select_noisy_indexes();
int noisy_index();
int count, selected,i;
int noisy_instance[7];
double actual;
srandom(seed);
instance=[ 1,1,1,0,1,1,1 ; 0,0,1,0,0,1,0
1,0,1,1,1,0,1 ; 1,0,1,1,0,1,1
0,1,1,1,0,1,0 ; 1,1,0,1,0,1,1
1,1,0,1,1,1,1 ; 1,0,1,0,0,1,0
1,1,1,1,1,1,1 ; 1,1,1,1,0,1,1 ]
fid = fopen(outputfile,"w");
for count = 0:numtrain
select_noisy_indexes();
selected = rem(random(),10);
for y = 0:7
noisy_instance(y) = instance(selected),(y);
if (noisy(y))
noisy_instance(y) = ~noisy_instance(y);
end
end
fprintf(fid,"%d,%d,%d,%d,%d,%d,%d,%d\n",noisy_instance(0),noisy_instance(1),noisy_instance(2),noisy_instance(3),noisy_instance(4),noisy_instance(5),noisy_instance(6));
for y =0:num_irrelevant_attributes
fprintf(fid,",%d",rem(random(),2));
fprintf(fid,",%d\n",selected);
end
end
actual = 100.0 * n/(7*numtrain);
printf("Percent Noise: Requested %d, Actual %f\n",percentnoise,actual);
fclose(fid);
end
function int = select_noisy_indexes()
int8 i;
double actual;
for i = 0:7
noisy(i) = 0;
if( ( 1 + (rem(random(),100))) <= percentnoise)
noisy(i) = 1;
n = n+1;
end
end
end
|
github
|
xiaoshaoning/LTE_Reed_Muller_code-master
|
LTE_Reed_Muller_encode.m
|
.m
|
LTE_Reed_Muller_code-master/LTE_Reed_Muller_encode.m
| 1,482 |
utf_8
|
7e6b6f81d01740fe71625bae883f67ff
|
% LTE O(32, 11) code for CQI/PMI and ACK
function y = LTE_Reed_Muller_encode(x)
basis_sequences_for_32_O = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1; ...
1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1; ...
1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1; ...
1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1; ...
1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1; ...
1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1; ...
1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1; ...
1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1; ...
1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1; ...
1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1; ...
1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1; ...
1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1; ...
1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1; ...
1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1; ...
1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1; ...
1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1; ...
1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0; ...
1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0; ...
1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0; ...
1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0; ...
1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1; ...
1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1; ...
1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1; ...
1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1; ...
1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0; ...
1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1; ...
1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0; ...
1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0; ...
1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0; ...
1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0; ...
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1; ...
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
y = mod(x * (basis_sequences_for_32_O(:, 1:length(x))).', 2);
end
|
github
|
xiaoshaoning/LTE_Reed_Muller_code-master
|
LTE_pucch_20_A_encode.m
|
.m
|
LTE_Reed_Muller_code-master/LTE_pucch_20_A_encode.m
| 1,093 |
utf_8
|
9ec873d2ee9ec5fd98f5a54ebdd34afc
|
% LTE pucch (20, A) code
function y = LTE_pucch_20_A_encode(x)
basis_sequences_for_20_A = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0; ...
1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0; ...
1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1; ...
1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1; ...
1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1; ...
1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1; ...
1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1; ...
1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1; ...
1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1; ...
1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1; ...
1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1; ...
1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1; ...
1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1; ...
1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1; ...
1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1; ...
1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1; ...
1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1; ...
1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1; ...
1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0; ...
1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0];
y = mod(x * (basis_sequences_for_20_A(:, 1:length(x))).', 2);
end
|
github
|
lcnbeapp/beapp-master
|
set_beapp_def.m
|
.m
|
beapp-master/set_beapp_def.m
| 28,266 |
utf_8
|
117d2385db5f9f74defeadbe405113d3
|
%% set_beapp_def
%
% initialize BEAPP grp_proc_info struct, which contains processing
% information for the whole dataset
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% The Batch Electroencephalography Automated Processing Platform (BEAPP)
% Copyright (C) 2015, 2016, 2017
%
% Developed at Boston Children's Hospital Department of Neurology and the
% Laboratories of Cognitive Neuroscience
%
% All rights reserved.
%
% This software is being distributed with the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU General
% Public License for more details.
%
% In no event shall Boston Children’s Hospital (BCH), the BCH Department of
% Neurology, the Laboratories of Cognitive Neuroscience (LCN), or software
% contributors to BEAPP be liable to any party for direct, indirect,
% special, incidental, or consequential damages, including lost profits,
% arising out of the use of this software and its documentation, even if
% Boston Children’s Hospital,the Laboratories of Cognitive Neuroscience,
% and software contributors have been advised of the possibility of such
% damage. Software and documentation is provided “as is.” Boston Children’s
% Hospital, the Laboratories of Cognitive Neuroscience, and software
% contributors are under no obligation to provide maintenance, support,
% updates, enhancements, or modifications.
%
% This program is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License (version 3) as
% published by the Free Software Foundation.
%
% You should receive a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
%
% Description:
% The Batch Electroencephalography Automated Processing Platform (BEAPP) is a modular,
% MATLAB-based software designed to facilitate flexible batch processing
% of baseline and event related EEG files for artifact removal and analysis.
% BEAPP is designed for users who are comfortable using the MATLAB
% environment to run software but does not require advanced programing
% knowledge.
%
% Contributors to BEAPP:
% April R. Levin, MD ([email protected])
% Adriana Méndez Leal ([email protected])
% Laurel Gabard-Durnam, PhD ([email protected])
% Heather M. O'Leary ([email protected])
%
% Correspondence:
% April R. Levin, MD
% [email protected]
%
%
% In publications, please reference:
% Levin AR., Méndez Leal A., Gabard-Durnam L., O'Leary, HM (2017) BEAPP: The Batch Electroencephalography Automated Processing Platform
% Manuscript in preparation
%
% Additional Credits:
% BEAPP utilizes functionality from the software listed below. Users who choose to run any of this
% software through BEAPP should cite the appropriate papers in any publications.
%
% EEGLAB Version 14.0.0b
% http://sccn.ucsd.edu/wiki/EEGLAB_revision_history_version_14
%
% Delorme A & Makeig S (2004) EEGLAB: an open source toolbox for analysis
% of single-trial EEG dynamics. Journal of Neuroscience Methods 134:9-21
%
% PREP pipeline Version 0.52
% https://github.com/VisLab/EEG-Clean-Tools
%
% Bigdely-Shamlo N, Mullen T, Kothe C, Su K-M and Robbins KA (2015)
% The PREP pipeline: standardized preprocessing for large-scale EEG analysis
% Front. Neuroinform. 9:16. doi: 10.3389/fninf.2015.00016
%
% CSD Toolbox
% http://psychophysiology.cpmc.columbia.edu/Software/CSDtoolbox/
%
% Kayser, J., Tenke, C.E. (2006). Principal components analysis of Laplacian
% waveforms as a generic method for identifying ERP generator patterns: I.
% Evaluation with auditory oddball tasks. Clinical Neurophysiology, 117(2), 348-368
%
% Users using low-resolution (less than 64 channel) montages with the CSD toolbox should also cite:
% Kayser, J., Tenke, C.E. (2006). Principal components analysis of Laplacian
% waveforms as a generic method for identifying ERP generator patterns: II.
% Adequacy of low-density estimates. Clinical Neurophysiology, 117(2), 369-380
%
% HAPP-E Version 1.0
% Gabard-Durnam L., Méndez Leal A., and Levin AR (2017) The Harvard Automated Pre-processing Pipeline for EEG (HAPP-E)
% Manuscript in preparation
% Requirements:
% BEAPP was written in Matlab 2016a. Older versions of Matlab may not
% support certain functions used in BEAPP.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function grp_proc_info = set_beapp_def
%% version numbers for BEAPP and packages
grp_proc_info.beapp_ver={'BEAPP_v4_1'};
grp_proc_info.eeglab_ver = {'eeglab14_1_2b'};
grp_proc_info.fieldtrip_ver = {'fieldtrip-20160917'};
grp_proc_info.beapp_root_dir = {fileparts(mfilename('fullpath'))}; %sets the directory to the BEAPP code assuming that it is in same directory as set_beapp_def
%% directory defaults and paths
grp_proc_info.beapp_pname={''}; %the Matlab paths where the BEAPP code is located
grp_proc_info.src_dir={''}; %source directory containing the EEG data exported from Netstation, left empty in defaults because it must be set by the user
grp_proc_info.beapp_genout_dir={''}; %general output directory that is used to store output when the directory that the output would normally be stored in is temporary
%% initialize module flags (which modules are on and off)
ModuleNames = {'format','prepp','filt','rsamp','ica','rereference','detrend','segment','psd','itpc','topoplot','fooof','pac','bycycle'};
Module_Input_Type = {'cont','cont','cont','cont','cont','cont','cont','cont','seg','seg','psd','psd','seg','seg'}'; %TODO: make output from psd 'psd'
Module_Output_Type ={'cont','cont','cont','cont','cont','cont','cont','seg','psd','out','out','out','out','out'}';
Mod_Names=ModuleNames(:);
Module_On = true(length(ModuleNames),1); % flag all modules on as default
Module_Export_On=false(length(ModuleNames),1); % set export to false as default
Module_Dir = cell(length(ModuleNames),1);
Module_Dir(:) = {''};
Module_Xls_Out_On= false(length(ModuleNames),1);
grp_proc_info.beapp_toggle_mods=table(Mod_Names,Module_On,Module_Export_On,Module_Xls_Out_On,Module_Dir,Module_Input_Type,Module_Output_Type);
grp_proc_info.beapp_toggle_mods.Properties.RowNames=ModuleNames;
clear ModuleNames Module_On Module_Export_On Module_Dir
clear Module_Xls_Out_On Mod_Names Module_Input_Type Module_Output_Type
%% initialize module and export toggles that are different from standard module on, export off
grp_proc_info.beapp_toggle_mods{'ica','Module_Xls_Out_On'}=1; % flag that toggles segment xls report option on
grp_proc_info.beapp_toggle_mods{'segment','Module_Xls_Out_On'}=1; % flag that toggles segment xls report option on
grp_proc_info.beapp_toggle_mods{'psd','Module_Export_On'}=1; %flag that toggles the data export option for the psd code
grp_proc_info.beapp_toggle_mods{'psd','Module_Xls_Out_On'}=1; % export psd to tables
grp_proc_info.beapp_toggle_mods{'itpc','Module_On'}=0; %turns ITPC analysis on, use with event data only
grp_proc_info.beapp_toggle_mods{'itpc','Module_Xls_Out_On'}=1; %flags the export data to xls option on
grp_proc_info.beapp_toggle_mods{'prepp','Module_Xls_Out_On'}=1; %flags the export data to xls option on
% coherence is not yet an option
%grp_proc_info.beapp_toggle_mods{'coh','Module_Xls_Out_On'}=0; %export coherence to tables
%grp_proc_info.beapp_toggle_mods{'coh',{'Module_On','Module_Export_On'}}=[0,0];% turns coherence off
%% paths for packages and tables
grp_proc_info.beapp_ft_pname={[grp_proc_info.beapp_root_dir{1},filesep,'Packages',filesep,grp_proc_info.eeglab_ver{1},filesep,grp_proc_info.fieldtrip_ver{1}]};
grp_proc_info.beapp_format_mff_jar_lib = [grp_proc_info.beapp_root_dir{1} filesep 'reference_data' filesep 'MFF-1.2.jar']; %the java class file needed when reading mff source files
grp_proc_info.ref_net_library_dir=[grp_proc_info.beapp_root_dir{1},filesep,'reference_data',filesep,'net_library'];
grp_proc_info.ref_net_library_options = ([grp_proc_info.beapp_root_dir{1},filesep,'reference_data',filesep,'net_library_options.mat']);
grp_proc_info.ref_eeglab_loc_dir = [grp_proc_info.beapp_root_dir{1},filesep, 'Packages',filesep,grp_proc_info.eeglab_ver{1},filesep, 'sample_locs'];
grp_proc_info.ref_def_template_folder = [fileparts(mfilename('fullpath')) filesep, 'run_templates'];
% initialize input tables: only necessary if inputs are .mats, non-uniform offset information is
% needed for mff files, or if you'd like to rerun a subselection of files
grp_proc_info.beapp_file_info_table =[grp_proc_info.beapp_root_dir{1} filesep 'user_inputs',filesep,'beapp_file_info_table.mat'];
grp_proc_info.rerun_file_info_table =[grp_proc_info.beapp_root_dir{1} filesep 'user_inputs',filesep,'rerun_fselect_table.mat'];
grp_proc_info.beapp_alt_beapp_file_info_table_location = {''};
grp_proc_info.beapp_alt_rerun_file_info_table_location = {''};
%% general defaults
grp_proc_info.beapp_advinputs_on=0; %flag that toggles advanced user options, default is 0 (user did not set advanced user values)
grp_proc_info.hist_run_tag = datetime('now'); % run_tag records when beapp was started
grp_proc_info.beapp_dir_warn_off = 0;
grp_proc_info.beapp_curr_run_tag = ''; % if you would like to append a tag to folder names for this run. If not given on a rerun, a timestamp will be used
grp_proc_info.beapp_prev_run_tag = ''; % run tag for previous run that you would like to use as source data for rerun. can be timestamp, but must be exact.
grp_proc_info.beapp_use_rerun_table = 0; % use rerun table to select subset of files previously run
grp_proc_info.seg_info_mff_src_dir = {''}; % for almost all users should be empty, functionality not supported
grp_proc_info.beapp_fname_all={''}; %list of beapp file names, set during get_beapp_srcflist
grp_proc_info.beapp_run_per_file = 0;
grp_proc_info.beapp_file_idx = 1;
%% general user setting defaults
grp_proc_info.beapp_rmv_bad_chan_on=0; %flag that removes channels that prepp/HAPPE identifies as bad, replace with NaNs
%% formatting/source file defaults
grp_proc_info.src_format_typ=1; %type of source file 1=.mat files, 2=mff, 3=PRE-PROCESSED + PRE-SEGMENTED MFF
grp_proc_info.src_data_type = 1; % type of data being processed (for segmenting,see user guide): 1 = baseline, 2 = event related
grp_proc_info.epoch_inds_to_process = []; % def = []. ex [1], [3,4]Index of desired epochs to analyze (for ex. if resting is always in the first epoch, for baseline analysis = [1]);
grp_proc_info.src_unique_nets={''}; % unique net names in dataset
grp_proc_info.src_fname_all={''}; %list of source file names, set during get_beapp_srcflist or as a user input
grp_proc_info.src_eeg_vname={'Category_1_Segment1','Category_1','EEG_Segment1','EEGSegment1'}; %variable name of the EEG data EEG_Segment1
grp_proc_info.src_format_typ=1; %type of source file 1=netstation, 2=mff, 3=mff in *.mat format, previously proc_info.beapp_format_typ
grp_proc_info.src_net_typ_all=[]; %list of net types from source files set in get_beapp_srcnettyp
grp_proc_info.src_srate_all=[]; %list of net types from source files set in get_beapp_srcsrate
grp_proc_info.src_linenoise=60; %line noise frequency in the source data, later replace with fft to test for 60 or 70
grp_proc_info.src_buff_start_nsec=2; %number of seconds buffer at the start of the EEG recording that can be excluded after filtering and artifact removal (buff1_nsec)- GROUP OR FILE?
grp_proc_info.src_buff_end_nsec=2; %number of seconds buffer at the end of the EEG recording that can be excluded after filtering and artifact removal (buff2_nsec) -GROUP OR FILE?
grp_proc_info.mff_seg_throw_out_bad_segments =1; % determines whether to throw out bad segments
grp_proc_info.src_presentation_software =1; % presentation software used for paradigm (0 = none, 1 = EPrime, 2 = Presentation, 3 = EEGLAB formatted (see user guide). def = 1)
grp_proc_info.beapp_indx_chans_to_exclude = {}; % index of channels to exclude in each net. def = {};
grp_proc_info.src_eeglab_cond_info_field = 'condition'; % name of field with condition information (ex .cel_type or .condition)
grp_proc_info.src_eeglab_latency_units =1; % units on EEGLAB .set file latency field. def=1; 1 = samples, 2 = seconds, 3 = milliseconds, 4 = microseconds
%% event formatting defaults
grp_proc_info.beapp_event_code_onset_strs={''}; %the event codes assigned during data collection to signifiy the onset of the stimulus
grp_proc_info.beapp_event_code_offset_strs={''}; %Ex {'TRSP'} the event codes assigned during data collection to signifiy the offset of the stimulus (should match onset strs)
grp_proc_info.beapp_event_eprime_values.condition_names = {''};
grp_proc_info.beapp_event_eprime_values.event_codes = []; % 2d array -- groups x condition codes
grp_proc_info.event_tag_offsets = 0; % def = 0 OR 'input_table'. Event offset in ms. If offset is not uniform across dataset, set to input_table and input information as in evt_file_info_table example
grp_proc_info.beapp_event_use_tags_only = 0; % def =0 (use event codes/tags/strings and condition/cel information). 1 = use event codes/tags/strings only for segmenting
%% Formatting specifications: Behavioral Coding
grp_proc_info.behavioral_coding.events = {''}; % def = {''}. Ex {'TRSP'} Events containing behavioral coding information
grp_proc_info.behavioral_coding.keys = {''}; % def = {''} Keys in events containing behavioral coding information
grp_proc_info.behavioral_coding.bad_value = {''}; % def = {''}. Value that marks behavioral coding as bad. must be string - number values must be listed as string, ex '1'
%% defaults for BEAPP filtering
Filt_Type = {'Lowpass','Highpass','Notch','Cleanline'}';
Filt_On = [1,1,1,0]';
Filt_Name = {'eegfilt','eegfilt','notch','cleanline'}';%equiripple FIR filter, eeglab filter, or notch filter
Filt_Attenpband = [1,nan,nan,nan]'; %attenuation in the passband in dB, not needed for EEGLab filter
Filt_Attensband = [60,nan,nan,nan]'; %attenuation in the stop band in dB, not needed for EEGLab filter
Filt_Cutoff_Freq =[100,1,nan,nan]'; % highest good frequency or lowest good frequency depending on highpass or lowpass
Filt_Lp_Filt=[nan,nan,nan,nan]'; %gets set inside batch_beapp_filt if lowpass is on
grp_proc_info.beapp_filters=table(Filt_On,Filt_Name,Filt_Cutoff_Freq,Filt_Lp_Filt);
grp_proc_info.beapp_filters.Properties.RowNames=Filt_Type;
clear Filt_Type Filt_On Filt_Name Filt_Attenpband Filt_Attensband Filt_Cutoff_Freq Filt_Lp_Filt Filt_Src_Linenoise
%% defaults for batch resampling
grp_proc_info.beapp_rsamp_typ='interpolation'; % set default, 'interpolation' or 'downsampling'
grp_proc_info.beapp_rsamp_srate=250; %sampling rate that all resampled files should have (1000 for U19, switch later)
grp_proc_info.beapp_rsamp_nsamp=[]; %number of samples after resampling
%% ICA variables
grp_proc_info.name_10_20_elecs = {'FP1','FP2','F7','F3','F4','F8','C3','C4','T5','PZ','T6','O1','O2','T3','T4','P3','P4','Fz'}; % does not include CZ
grp_proc_info.name_selected_10_20_chans_lbls = {grp_proc_info.name_10_20_elecs}; %by default, include all 10-20, later beapp will check if current net doesn't include all and update variable
grp_proc_info.beapp_ica_type = 1; % 1 = ICA with MARA, 2 = HAPPE, 3 = only ICA
grp_proc_info.beapp_ica_run_all_10_20 = 1;
grp_proc_info.beapp_ica_10_20_chans_lbls{1} = [];
grp_proc_info.beapp_ica_additional_chans_lbls{1}= []; %additional channels to use in ICA module besides 10-20
grp_proc_info.happe_plotting_on = 0 ; % if 1, plot visualizations from MARA, require user input
%% rereference module defaults
grp_proc_info.reref_typ = 1; %average reference as default
% CSD laplacian defaults
grp_proc_info.beapp_csdlp_interp_flex=4; %m=2...10, 4 spline
grp_proc_info.beapp_csdlp_lambda=1e-5; %learning rate def = 1e-5;
% Rows in eeg corresponding to desired reference channel for each net (only used if reref_typ = 3)
% MUST match number of nets and order of nets in .src_unique nets exactly ex {[57,100],[51,26]};
grp_proc_info.beapp_reref_chan_inds = {[]}; % def = {[]};
%% defaults for detrending
grp_proc_info.dtrend_typ=1; %type of detrending method to use (0=no detrend, 1=mean, 2=linear, 3=Kalman)
grp_proc_info.kalman_b=0.9999; %used to determine smoothing in the Kalman filter, use 0.995 as alternative
grp_proc_info.kalman_q_init=1; %used to determine smoothing in Kalman filter
%% segmentation defaults
grp_proc_info.beapp_reject_segs_by_amplitude= 0; % def = 1; flag that toggles amplitude-based rejection of segments after segment creation
grp_proc_info.art_thresh=150; %threshold in uV for artifact (scale will need to change if using CSDLP)
grp_proc_info.segment_linear_detrend = 0; % apply linear detrend to segments in segmentation module 0 off, 1 = linear, 2 = mean detrend
grp_proc_info.beapp_happe_segment_rejection = 0; %def = 0; eeg_thresh and jointprob rejection after segmentation
grp_proc_info.beapp_happe_seg_rej_plotting_on = 0; % def = 0; visualizations during joint prob
%% defaults for baseline segmentation module
% flag that toggles the removal of high-amplitude artifact before segmentation (only used for baseline)
grp_proc_info.beapp_baseline_msk_artifact=1; % def = 1; 0= off, 1 = on, 2 = by percent
% percent (0-100) of channels being analyzed above threshold required to mask sample for pre-segmentation rejection
grp_proc_info.beapp_baseline_rej_perc_above_threshold = .01; % def = .01; (.01%, should reject if any channels bad assuming channel # <1000)
grp_proc_info.win_size_in_secs=1; % length of windows for segmenting (baseline length of good data needed)
%% defaults for event segmentation module
grp_proc_info.beapp_erp_maf_on=0; %flags on the moving average filter when the ERP events are generated
grp_proc_info.beapp_erp_maf_order=30; %Order of the moving average filter
grp_proc_info.evt_seg_win_start = -0.100; % def = -0.100; start time in seconds for segments, relative to the event marker of interest (ex -0.100, 0)
grp_proc_info.evt_seg_win_end = 0.800; % def = .800; end time in seconds for segments, relative to the event marker of interest (ex .800, 1)
%Set which event data to analyze, relative to the event marker of interest (This can be the whole segment, or part of a segment)
grp_proc_info.evt_analysis_win_start = -0.100; % def = -0.100; start time in seconds for analysis segments, relative to the event marker of interest (ex -0.100, 0)
grp_proc_info.evt_analysis_win_end = 0.800; % def = .800; end time in seconds for analysis segments, relative to the event marker of interest (ex .800, 1)
%Set which event data is baseline
grp_proc_info.evt_trial_baseline_removal = 0; % def = 0; flag on use of pop_rmbaseline in segmentation module.
grp_proc_info.evt_trial_baseline_win_start = -.100; % def = -0.100; start time in seconds for baseline, relative to the event marker of interest (ex -0.100, 0). Must be within range you've segmented on.
grp_proc_info.evt_trial_baseline_win_end = 0; % def = 0; start time in seconds for baseline, relative to the event marker of interest (ex -0.100, 0)
%Option to segment on nth trial
grp_proc_info.select_nth_trial = [];
grp_proc_info.segment_stim_relative_to = {''};
grp_proc_info.segment_nth_stim_str = {''};
grp_proc_info.beapp_event_group_stim=0;
%% variables for general output module processing
%OUTPUT MEASURE SPECIFICATIONS
% trial selection specifications
% select n of usable segments PER CONDITION to use for output measure
% [] = use all possible segments, n = use specific number, discard file if file has
% fewer than n
grp_proc_info.win_select_n_trials = [];
% def = 0; select number of trials based on segments pre-rejection
% (automatically 0 for resting)
% 1 = select trials after segment rejection
grp_proc_info.win_select_trials_post_rej = 0;
% select trials from trial range ex[25,50];. def = []; (select at random)
% if .win_select_trials_post_rej = 1, trial ranges will apply to good
% trials after rejection
grp_proc_info.win_select_trials_in_range = [];
%removed the option of reusing previously calculated frequency info
grp_proc_info.bw(1,1:2)=[2,4]; %bandwidth 1 start and end frequencies (the first band), can have as many or as few bandwidths as the user would like
grp_proc_info.bw_name(1)={'Delta'}; %name of bandwidth 1
grp_proc_info.bw_total_freqs = [1:100]; % frequencies to include in calculation of total power (for normalization). def = [1:100].
grp_proc_info.win_select_n_trials = []; % use all available trials
%% PSD default variables
grp_proc_info.psd_output_typ = 1; % psd = 1, power = 2, def = 1
grp_proc_info.psd_win_typ=1; %windowing type 0=rectangular window, 1=hanning window, 2=multitaper (recomended 2 seconds or longer)
grp_proc_info.psd_interp_typ=1; %type of interpolation of psd 1 none, 2 linear, 3 nearest neighbor, 4 piecewise cubic spline
grp_proc_info.psd_interp_typ_name(1)={'None'}; %no interpolation
grp_proc_info.psd_interp_typ_name(2)={'linear'}; %linear interpolation, the default in current and previous versions of BEAPP
grp_proc_info.psd_interp_typ_name(3)={'nearest'}; %nearest neighbor
grp_proc_info.psd_interp_typ_name(4)={'spline'}; %piecewise cubic spline
grp_proc_info.psd_nfft=[]; %number of sample points used for the fft, wil be set in the batch_beapp_psd
grp_proc_info.psd_baseline_normalize = 0;
%variables needed for the PSD Multitaper option
grp_proc_info.psd_pmtm_l=3; %number of tapers to use in the multitaper, positive int 3 or greater
grp_proc_info.psd_pmtm_alpha=[]; %alpha used in multitaper, if alpha=2 and nsec=2 then L=3 tapers and spectral resolution is 2
grp_proc_info.psd_pmtm_r=[]; %the spectral resolution of the power clculated from the PSD multitaper method
%% variables for writing PSD data into xls sheets or csv
grp_proc_info.beapp_xlsout_ntab=1; %this is determined by the number of types of outputs to write into a single workbook, may remove this in the future
grp_proc_info.beapp_xlsout_hdr={'FileName','NetType','ArtifactThreshold','DetrendType','WindowSizeSeconds','WindowType','NumberOfObservations'};% header for values generated in reports
grp_proc_info.beapp_xlsout_av_on=1; %toggles on the mean power option
grp_proc_info.beapp_xlsout_sd_on=0; %toggles on the standard deviation option
grp_proc_info.beapp_xlsout_med_on=1; %toggles on the median option
grp_proc_info.beapp_xlsout_raw_on=1; %toggles on that the absolute power should be reported
grp_proc_info.beapp_xlsout_norm_on=1; %toggles on that the normalized power should be reported
grp_proc_info.beapp_xlsout_log_on=0; %toggles on that the natural log should be reported
grp_proc_info.beapp_xlsout_log10_on=1; %toggles on that the log10 should be reported
grp_proc_info.beapp_xlsout_elect_indx=1:129; %Channel numbers for the report. If the channel numbers are net dependent then report all possible net channel numbers for all nets, can't specify different channels for different nets
%% ITPC default variables
grp_proc_info.beapp_itpc_params.win_size=0.256;%64; %the win_size (in seconds) to calculate ERSP and ITPC from the ERPs of the composed dataset (e.g. should result in a number of samples an integer and divide trials equaly ex: 10)
grp_proc_info.beapp_itpc_xlsout_mx_on=1; % report max itpc
grp_proc_info.beapp_itpc_xlsout_av_on=1; % report mean itpc
grp_proc_info.beapp_itpc_params.baseline_norm=1;
grp_proc_info.beapp_itpc_params.use_common_baseline=0;
grp_proc_info.beapp_itpc_params.common_baseline_idx=1;
grp_proc_info.beapp_itpc_params.set_freq_range=0;
grp_proc_info.beapp_itpc_params.min_freq= 2;
grp_proc_info.beapp_itpc_params.max_freq=50;
grp_proc_info.beapp_itpc_params.min_cyc=1;
grp_proc_info.beapp_itpc_params.max_cyc=8;
%% FOOOF default variables
grp_proc_info.fooof_min_freq = 1; %The frequency range of the psd fooof will run on
grp_proc_info.fooof_max_freq = 50;
grp_proc_info.fooof_peak_width_limits = [0,10]; %Set peak width limit to prevent overfitting. Needs to be > frequency resolution
grp_proc_info.fooof_max_n_peaks = 6; %Set a max number of peaks for fooof to find to prevent overfitting -- some maximum must be set
grp_proc_info.fooof_min_peak_amplitude = 0; %Set a min peal amplitude for fooof to find to prevent overfitting
grp_proc_info.fooof_min_peak_threshold = 0; %Set to a number > 0 to set a min peak threshold -- recommended to set if psd has no peaks. Otherwise keep 0
grp_proc_info.fooof_background_mode = 2; %1 = fixed, 2 = knee; If freq range is ~40Hz or below, recommended to use 'fixed'; otherwise, use 'knee'
grp_proc_info.fooof_save_all_reports = 1; %0 to not save reports; 1 if all reports should be saved
grp_proc_info.fooof_save_participants = {}; %Specify for which participants reports should be saved. Ex: {'baselineEEG01.mat'}
grp_proc_info.fooof_save_channels = []; %Specify to only save reports for some channel #'s. Ex: [1,2] save reports from channels 1 and 2; [] to not specify channels
grp_proc_info.fooof_save_groups = []; %Specify to only save reports for group #'s specified. Ex: [1,3]
grp_proc_info.fooof_xlsout_on = 0; %1 if excel reports should be saved, 0 if not
grp_proc_info.fooof_average_chans = 0; %1 if channels should be averaged; 0 if they should be run seperately
grp_proc_info.fooof_channel_groups = {}; %Ex: {[8,9,10],[15,16,17,18,19,20]}; if averaging is on, but channels should be averaged in seperate groups; leave as {} if channels should be averaged together
grp_proc_info.fooof_chans_to_analyze = []; %list channels to analyze if only some channels should be analyzed; else, leave as []
%% PAC default variables
grp_proc_info.pac_low_fq_min = 1; %Minimum frequency of the low frequency to calculate
grp_proc_info.pac_low_fq_max = 10; %Maximum frequency of the low frequency to calculate
grp_proc_info.pac_low_fq_res = 50; %The # of frequencies to calculate between the min and max;Ex: to calculate for frequencies 1-10, set min to 1, max to 10, and res to 10
grp_proc_info.pac_high_fq_min = 10; %Minimum frequency of the low frequency to calculate
grp_proc_info.pac_high_fq_max = 125; %Maximum frequency of the low frequency to calculate
grp_proc_info.pac_high_fq_res = 50; %The # of frequencies to calculate between the min and max;Ex: to calculate for frequencies 1-10, set min to 1, max to 10, and res to 10
grp_proc_info.pac_method = 'tort'; %Can be: 'ozkurt', 'canolty', 'tort', 'penny', 'vanwijk', 'duprelatour', 'colgin', 'sigl', 'bispectrum'
grp_proc_info.pac_low_fq_width = 2.0; %Bandwidth of the bandpass filter for the lower frequency
grp_proc_info.pac_high_fq_width = 20; %Bandwidth of the bandpass filter for the higher frequency
grp_proc_info.pac_save_all_reports = 1;
grp_proc_info.pac_save_participants = {}; %Specify for which participants reports should be saved; {} to not specify participants. Ex: {'baselineEEG01.mat'}
grp_proc_info.pac_save_channels = []; %Specify to only save reports for some channel #'s. Ex: [1,2] save reports from channels 1 and 2; [] to not specify channels
grp_proc_info.pac_xlsout_on = 0; %1 if excel reports should be saved, 0 if not.
grp_proc_info.pac_chans_to_analyze = []; %list channels to analyze if only some channels should be analyzed; else, leave as []
grp_proc_info.slid_win_sz = 1;
grp_proc_info.slid_win_on = 0; %turn on to measure pac across time
grp_proc_info.pac_set_num_segs = 0; %choose whether a set the number of segments should be used for pac
grp_proc_info.pac_num_segs = 6; %if set_num_segs is on: set the number of segments to use for pac
grp_proc_info.pac_calc_zscores = 0;
grp_proc_info.pac_calc_btwn_chans = 0; %Compute PAC between 2 channels, instead of within each channel (BETA)
grp_proc_info.pac_variable_hf_filt = 0;
grp_proc_info.pac_save_amp_dist = 0; %save the binned high frequency amplitude distribution
%% Bycycle default methods
grp_proc_info.bycyc_set_num_segs = 0;
grp_proc_info.bycyc_num_segs = 0;
grp_proc_info.bycycle_freq_bands = [12,14]; %Ex: 6,8;8,10.
grp_proc_info.bycycle_gen_reports = true;
grp_proc_info.bycycle_save_reports = true;
grp_proc_info.bycycle_burstparams.amplitude_fraction_threshold = .3;
grp_proc_info.bycycle_burstparams.amplitude_consistency_threshold = .4;
grp_proc_info.bycycle_burstparams.period_consistency_threshold = .5;
grp_proc_info.bycycle_burstparams.monotonicity_threshold = .8;
grp_proc_info.bycycle_burstparams.N_cycles_min = 3;
end
|
github
|
lcnbeapp/beapp-master
|
fooof_group.m
|
.m
|
beapp-master/functions/fooof_group.m
| 1,475 |
utf_8
|
974a8666887be9f1b2a2c5bdc3238423
|
% fooof_group() run the fooof model on a group of neural power spectra
%
% Usage:
% fooof_results = fooof_group(freqs, psds, f_range, settings);
%
% Inputs:
% freqs = row vector of frequency values
% psds = matrix of power values, which each row representing a spectrum
% f_range = fitting range (Hz)
% settings = fooof model settings, in a struct, including:
% settings.peak_width_limts
% settings.max_n_peaks
% settings.min_peak_amplitude
% settings.peak_threshold
% settings.background_mode
% settings.verbose
%
% Outputs:
% fooof_results = fooof model ouputs, in a struct, including:
% fooof_results.background_params
% fooof_results.peak_params
% fooof_results.gaussian_params
% fooof_results.error
% fooof_results.r_squared
%
% Notes
% Not all settings need to be set. Any settings that are not
% provided as set to default values. To run with all defaults,
% input settings as an empty struct.
function fooof_results = fooof_group(freqs, psds, f_range, settings)
% Check settings - get defaults for those not provided
settings = fooof_check_settings(settings);
% Initialize object to collect FOOOF results
fooof_results = [];
% Run FOOOF across the group of power spectra
for psd = psds
cur_results = fooof(freqs, psd', f_range, settings);
fooof_results = [fooof_results, cur_results];
end
end
|
github
|
lcnbeapp/beapp-master
|
extract_num_attended_trials_pre_seg_rej.m
|
.m
|
beapp-master/functions/extract_num_attended_trials_pre_seg_rej.m
| 3,538 |
utf_8
|
f9e3f1ebf9c4a03d8aca5fafe122e199
|
% patch code to pull out behavioral coding information
% from BEAPP files retroactively, and stores them in a table (one for all
% files and conditions) in the out folder
% this information will eventually be included in BEAPP reporting
%
% src_dir is the string with the directory that contains the BEAPP source
% files of interest (ex. C:\my_src_dir\psd). Should be segment directory or
% an output directory
%
% condition_names is the cell array, equivalent to
% what grp_proc_info.beapp_event_eprime_values.condition_names. Condition
% names used should be identical to those used during initial file
% segmentation (order doesn't matter). If set to '', function will
% use whatever conditions were selected during segmentation for the first
% file in the folder
% example = extract_num_attended_trials_pre_seg_rej
% ('C:\beapp_dev\U19_EEG\segment', {'Rest'});
% to use conditions in the first file for all:
% extract_num_attended_trials_pre_seg_rej('C:\beapp_dev\U19_EEG\segment', '');
function extract_num_attended_trials_pre_seg_rej (src_dir, condition_names)
cd (src_dir);
flist = dir('*.mat');
flist = {flist.name};
if ~strcmp(condition_names,'')
output_table_cell = NaN(length(flist),length(condition_names)+1);
output_table = array2table(output_table_cell);
output_table.Properties.VariableNames = horzcat({'FileName'},strcat(condition_names,'_Num_Attended_Trials'));
output_table.FileName = flist';
end
for curr_file = 1:length(flist)
load(flist{curr_file},'file_proc_info');
if strcmp (condition_names, '')
condition_names = file_proc_info.grp_wide_possible_cond_names_at_segmentation;
output_table_cell = NaN(length(flist),length(condition_names)+1);
output_table = array2table(output_table_cell);
output_table.Properties.VariableNames = horzcat({'FileName'},strcat(condition_names,'_Num_Attended_Trials'));
output_table.FileName = flist';
end
evt_as_cell = cellfun(@(x) permute(squeeze(struct2cell(x)),[2 1]), file_proc_info.evt_info,'UniformOutput',0);
stacked_evt_tags = vertcat(evt_as_cell{:});
behavioral_coding_column = find(ismember (fieldnames(file_proc_info.evt_info{1}),'behav_code'));
type_column = find(ismember(fieldnames(file_proc_info.evt_info{1}),'type'));
attended_trial_inds = find(cellfun(@(x) x==0,stacked_evt_tags(:,behavioral_coding_column)));
for curr_condition = 1:length(condition_names)
% indices of condition
inds_cond = find(ismember(stacked_evt_tags(:,type_column),condition_names{curr_condition}));
% number of good trials for this condition
tot_att_for_cond_pre_rej = length(intersect(inds_cond,attended_trial_inds));
% store in table
output_table{curr_file, strcat(condition_names{curr_condition},'_Num_Attended_Trials')} = tot_att_for_cond_pre_rej;
end
clear file_proc_info tot_att_for_cond_pre_rej inds_cond attended_trial_inds type_column behavioral_coding_column stacked_evt_tags...
evt_as_cell
end
[modpath,mod_dir] = fileparts(src_dir);
outdir_str_split = strsplit (mod_dir,'_');
outdir_str_split = length(outdir_str_split{1});
run_tag = mod_dir(outdir_str_split +1 :end);
if ~isempty(run_tag)
run_tag = ['_' run_tag];
end
outdir_path = [modpath filesep 'out' run_tag];
if ~isdir(outdir_path)
mkdir(outdir_path);
end
cd(outdir_path);
writetable (output_table, ['All_Conditions_Num_Attended_Trials(Patch)' run_tag '.csv']);
|
github
|
lcnbeapp/beapp-master
|
wICA.m
|
.m
|
beapp-master/functions/wICA.m
| 4,582 |
utf_8
|
09e191d185eef1f2e79c7eed7d143029
|
%function [wIC,A,W,IC] = wICA(data, type= 'fastica', plotting= 1, Fs= 250, L=5)
function [wIC,A,W,IC] = wICA(EEG,varargin)
%--------------- function [wIC,A,W] = wICA(data,varargin) -----------------
%
% Performs ICA on data matrix (row vector) and subsequent wavelet
% thresholding to remove low-amplitude activity from the computed ICs.
% This is useful for extracting artifact-only ICs in EEG (for example), and
% then subtracting the artifact-reconstruction from the original data.
%
% >>> INPUTS >>>
% Required:
% data = data matrix in row format
% Optional:
% type = "fastica" or "radical"...two different ICA algorithms based on
% entropy. "fastica" (default) is parametric, "radical" is nonparametric.
% mult = threshold multiplier...multiplies the computed threshold from
% "ddencmp" by this number. Higher thresh multipliers = less
% "background" (or low amp. signal) is kept in the wICs.
% plotting = 1 or 0. If 1, plots wIC vs. non-wavelet thresholded ICs
% Fs = sampling rate, (for plotting...default = 1);
% L = level set for stationary wavelet transform. Higher levels give
% better frequency resolution, but less temporal resolution.
% Default = 5
% wavename = wavelet family to use. type "wavenames" to see a list of
% possible wavelets. (default = "coif5");
%
% <<< OUTPUTS <<<
% wIC = wavelet-thresholded ICs
% A = mixing matrix (inv(W)) (optional)
% W = demixing matrix (inv(A)) (optional)
% IC = non-wavelet ICs (optional)
%
% * you can reconstruct the artifact-only signals as:
% artifacts = A*wIC;
% - upon reconstruction, you can then subtract the artifacts from your
% original data set to remove artifacts, for instance.
%
% Example:
% n = rand(10,1000);
% a = [zeros(1,400),[.5,.8,1,2,2.4,2.5,3.5,5,6.3,6,4,3.2,3,1.7,1,-.6,-2.2,-4,-3.6,-3,-1,0],zeros(1,578)];
% data = n + linspace(0,2,10)'*a;
% [wIC,A] = wICA(data,[],5,1);
% ahat = A*wIC;
% nhat = data-ahat;
% err = sum(sqrt((nhat-n).^2));
% By JMS, 11/10/2015
%---------------------------------------------------------------------------------------
% check inputs
if nargin>1 && ~isempty(varargin{1})
type=varargin{1}; else type='runica';end
if nargin>2 && ~isempty(varargin{2})
mult=varargin{2};else mult=1;end
if nargin>3 && ~isempty(varargin{3})
plotting=varargin{3}; else plotting=0;end
if nargin>4 && ~isempty(varargin{4})
Fs=varargin{4};else Fs=1;end
if nargin>5 && ~isempty(varargin{5})
L=varargin{5}; else L=5;end
if nargin>6 && ~isempty(varargin{6})
wavename=varargin{6}; else wavename='coif5';end
% run ICA using "runica" or "radical"
if strcmp(type,'runica')
[OUTEEG, com] = pop_runica(EEG, 'extended',1,'interupt','on','verbose', 'off'); %runica for parametric, default extended for finding subgaussian distributions
W = OUTEEG.icaweights*OUTEEG.icasphere;
A = inv(W);
IC=reshape(OUTEEG.icaact, size(OUTEEG.icaact,1), []);
%com = pop_export(OUTEEG,'ICactivationmatrix','ica','on','elec','off','time','off','precision',4);
%IC = ICactivationmatrix;
elseif strcmp(type,'radical')
[IC,W] = radical(data); % radical ICA for non-parametric
A = inv(W);
end
% padding data for proper wavelet transform...data must be divisible by
% 2^L, where L = level set for the stationary wavelet transform
modulus = mod(size(IC,2),2^L); %2^level (level for wavelet)
if modulus ~=0
extra = zeros(1,(2^L)-modulus);
else
extra = [];
end
% loop through ICs and perform wavelet thresholding
disp('Performing wavelet thresholding');
for s = 1:size(IC,1)
if ~isempty(extra)
sig = [IC(s,:),extra]; % pad with zeros
else
sig = IC(s,:);
end
[thresh,sorh,~] = ddencmp('den','wv',sig); % get automatic threshold value
thresh = thresh*mult; % multiply threshold by scalar
swc = swt(sig,L,wavename); % use stationary wavelet transform (SWT) to wavelet transform the ICs
Y = wthresh(swc,sorh,thresh); % threshold the wavelet to remove small values
wIC(s,:) = iswt(Y,wavename); % perform inverse wavelet transform to reconstruct a wavelet IC (wIC)
clear y sig thresh sorh swc
end
% remove extra padding
if ~isempty(extra)
wIC = wIC(:,1:end-numel(extra));
end
% plot the ICs vs. wICs
if plotting>0
disp('Plotting');
subplot(3,1,1);
multisignalplot(IC,Fs,'r');
title('ICs');
subplot(3,1,2);
multisignalplot(wIC,Fs,'r');
title('wICs')
subplot(3,1,3);
multisignalplot(IC-wIC,Fs,'r');
title('Difference (IC - wIC)');
end
end
|
github
|
lcnbeapp/beapp-master
|
beapp_pre_segmentation_version_control.m
|
.m
|
beapp-master/functions/beapp_pre_segmentation_version_control.m
| 1,136 |
utf_8
|
b3b0e3c992754c0e21d1444d3a91efe7
|
% version control for BETA testers BEAPP 4.0
function file_proc_info = beapp_pre_segmentation_version_control (file_proc_info)
file_proc_info.beapp_nchans_used = cellfun(@length,file_proc_info.beapp_indx,'UniformOutput',1)';
if ~isfield(file_proc_info, 'evt_header_tag_information')
file_proc_info.evt_header_tag_information = [];
end
[~,~,src_file_ext] =fileparts(file_proc_info.src_fname{1});
if isfield(file_proc_info,'evt_info') && isequal('.mff',src_file_ext)
% fix event sample numbers (offset calculations were off in previous
% versions of mff reader)
for curr_epoch = 1:size(file_proc_info.evt_info,2)
if ~isempty(file_proc_info.evt_info{curr_epoch})
for curr_event = 1:length(file_proc_info.evt_info{curr_epoch})
file_proc_info.evt_info{curr_epoch}(curr_event).evt_times_samp_rel = round(double(time2samples(file_proc_info.evt_info{curr_epoch}(curr_event).evt_times_micros_rel,...
file_proc_info.beapp_srate,6,'round')) + round(file_proc_info.src_file_offset_in_ms *(file_proc_info.beapp_srate/1000))+1);
end
end
end
end
|
github
|
lcnbeapp/beapp-master
|
batch_beapp_ica.m
|
.m
|
beapp-master/functions/batch_beapp_ica.m
| 14,199 |
utf_8
|
7d6826925a40b39559ef854cdd029edd
|
%% batch_beapp_ica (grp_proc_info)
%
% Apply ICA + MARA, HAPPE, or ICA to the data according to
% grp_proc_info.ica_type, generate output report if user selected
%
% ICA+ MARA and HAPPE outputs will have backprojected components
% output for ICA alone will be raw data + ICA weights and sphere matrices
%
% HAPP-E Version 1.0
% Gabard-Durnam LJ, Méndez Leal AS, and Levin AR (2017) The Harvard Automated Pre-processing Pipeline for EEG (HAPP-E)
% Manuscript in preparation
%
% MARA
% Irene Winkler, Stefan Haufe and Michael Tangermann. Automatic Classification of Artifactual
% ICA-Components for Artifact Removal in EEG Signals. Behavioral and Brain Functions, 7:30, 2011.
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% The Batch Electroencephalography Automated Processing Platform (BEAPP)
% Copyright (C) 2015, 2016, 2017
% Authors: AR Levin, AS Méndez Leal, LJ Gabard-Durnam, HM O'Leary
%
% This software is being distributed with the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU General
% Public License for more details.
%
% In no event shall Boston Children’s Hospital (BCH), the BCH Department of
% Neurology, the Laboratories of Cognitive Neuroscience (LCN), or software
% contributors to BEAPP be liable to any party for direct, indirect,
% special, incidental, or consequential damages, including lost profits,
% arising out of the use of this software and its documentation, even if
% Boston Children’s Hospital,the Laboratories of Cognitive Neuroscience,
% and software contributors have been advised of the possibility of such
% damage. Software and documentation is provided “as is.” Boston Children’s
% Hospital, the Laboratories of Cognitive Neuroscience, and software
% contributors are under no obligation to provide maintenance, support,
% updates, enhancements, or modifications.
%
% This program is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License (version 3) as
% published by the Free Software Foundation.
%
% You should receive a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function grp_proc_info_in = batch_beapp_ica(grp_proc_info_in)
src_dir = find_input_dir('ica',grp_proc_info_in.beapp_toggle_mods);
% initialize report. depending on setting some values will not be generated
if grp_proc_info_in.beapp_toggle_mods{'ica','Module_Xls_Out_On'}
if grp_proc_info_in.beapp_toggle_mods{'ica','Module_Xls_Out_On'}
ica_report_categories = {'BEAPP_Fname','Time_Elapsed_For_File','Num_Rec_Periods', 'Number_Channels_UserSelected',...
'File_Rec_Period_Lengths_In_Secs','Number_Good_Channels_Selected_Per_Rec_Period', ...
'Interpolated_Channel_IDs_Per_Rec_Period', 'Percent_ICs_Rejected_Per_Rec_Period', ...
'Percent_Variance_Kept_of_Data_Input_to_MARA_Per_Rec_Period', ...
'Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period','Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period'};
ICA_report_table= cell2table(cell(length(grp_proc_info_in.beapp_fname_all),length(ica_report_categories)));
ICA_report_table.Properties.VariableNames=ica_report_categories;
ICA_report_table.BEAPP_Fname = grp_proc_info_in.beapp_fname_all';
end
end
% add path to cleanline
if exist('cleanline', 'file')
cleanline_path = which('eegplugin_cleanline.m');
cleanline_path = cleanline_path(1:findstr(cleanline_path,'eegplugin_cleanline.m')-1);
addpath(genpath(cleanline_path));
end
for curr_file=1:length(grp_proc_info_in.beapp_fname_all)
tic
cd(src_dir{1})
if exist(strcat(src_dir{1},filesep,grp_proc_info_in.beapp_fname_all{curr_file}),'file')
try
load(grp_proc_info_in.beapp_fname_all{curr_file},'eeg','file_proc_info');
catch
disp('Problem Loading')
pause(5)
load(grp_proc_info_in.beapp_fname_all{curr_file},'eeg','file_proc_info');
end
tic;
% epoch_length = file_proc_info.src_epoch_nsamps / file_proc_info.src_srate;
% if epoch_length < 15 && ~grp_proc_info_in.beapp_ica_type==3
% warning(strcat('Current file length=',num2str(epoch_length),...
% '_seconds. MARA requires at least 15 seconds of data to work correctly'))
% end
%FOR TESTING
uniq_net_ind = find(strcmp(grp_proc_info_in.src_unique_nets, file_proc_info.net_typ{1}));
ica_chan_labels_in_eeglab_format = {file_proc_info.net_vstruct(grp_proc_info_in.beapp_ica_additional_chans_lbls{uniq_net_ind}).labels};
% use_all_10_20s = 1;
% if grp_proc_info_in.beapp_ica_type == 3 && grp_proc_info_in.beapp_ica_run_all_10_20 == 0
% use_all_10_20s = 0;
% end
%%REMOVES REPETITIVE CHANS (WILL BREAK HAPPE IF PRESENT)
chans2remove = [];
rmv_idx = 1;
for chan1 = 1:size(eeg{1,1},1)
for chan2 = 1:size(eeg{1,1},1)
if ~(chan1 == chan2)
% if ~(any(eeg{1,1}(chan1,:) == eeg{1,1}(chan2,:)==0))
if (sum(eeg{1,1}(chan1,:) == eeg{1,1}(chan2,:))) > size(eeg{1,1})/2
chans2remove(1,rmv_idx) = chan1;
rmv_idx = rmv_idx+1;
end
end
end
end
chans2remove = unique(chans2remove);
grp_proc_info_in.beapp_indx_chans_to_exclude{1,1} = chans2remove;
if ~isempty(chans2remove)
warning(['Channels ' num2str(chans2remove) ' demonstrated identical or no data; those channels were removed from further analysis']);
end
% select channels depending on user settings
[chan_IDs, file_proc_info] = beapp_ica_select_channels_for_file (file_proc_info,grp_proc_info_in.src_unique_nets,...
ica_chan_labels_in_eeglab_format,grp_proc_info_in.name_10_20_elecs,grp_proc_info_in.beapp_indx_chans_to_exclude,...
grp_proc_info_in.beapp_ica_run_all_10_20,grp_proc_info_in.beapp_ica_10_20_chans_lbls,grp_proc_info_in.name_selected_10_20_chans_lbls);
for curr_rec_period = 1:size(eeg,2)
% make EEGLAB struct, change 10-20 electrode labels for MARA
EEG_orig = curr_epoch_beapp2eeglab(file_proc_info,eeg{curr_rec_period},curr_rec_period);
% if HAPPE, run 1-250 bandpass filter, cleanline, and reject channels
% either way, select EEG channels of interest for analyses
if grp_proc_info_in.beapp_ica_type == 2
[EEG_tmp, full_selected_channels,file_proc_info.beapp_filt_max_freq] = happe_bandpass_cleanline_rejchan (EEG_orig,chan_IDs,...
file_proc_info.beapp_srate, file_proc_info.src_linenoise,file_proc_info.beapp_filt_max_freq);
else
EEG_tmp = pop_select(EEG_orig,'channel', chan_IDs);
full_selected_channels = EEG_tmp.chanlocs;
diary off;
end
if grp_proc_info_in.beapp_rmv_bad_chan_on
[chan_name_indx_dict(:,1), file_proc_info.beapp_indx{curr_rec_period}] = intersect({file_proc_info.net_vstruct.labels},{EEG_tmp.chanlocs.labels},'stable');
else
[chan_name_indx_dict(:,1), file_proc_info.beapp_indx{curr_rec_period}] = intersect({file_proc_info.net_vstruct.labels},{full_selected_channels.labels},'stable');
end
% save reporting information
ica_report_struct.good_chans_per_rec_period(curr_rec_period) = length({EEG_tmp.chanlocs.labels});
ica_report_struct.rec_period_lengths_in_secs(curr_rec_period) = (length(eeg{curr_rec_period})/file_proc_info.beapp_srate);
ica_report_struct.num_interp_per_rec_period(curr_rec_period) = length(chan_IDs) - length({EEG_tmp.chanlocs.labels});
% save channels used in file_proc_info
file_proc_info.beapp_nchans_used(curr_rec_period) = length(file_proc_info.beapp_indx{curr_rec_period});
chan_name_indx_dict(:,2) = num2cell(file_proc_info.beapp_indx{curr_rec_period});
[~,ind_marked_bad_chans]= intersect({file_proc_info.net_vstruct.labels},setdiff({full_selected_channels.labels},{EEG_tmp.chanlocs.labels}),'stable');
%ERROR REPORTED HERE: horzcat error; ind_marked_bad_chans was a
%column, can't be concatenated with a row
file_proc_info.beapp_bad_chans{curr_rec_period} = unique([file_proc_info.beapp_bad_chans{curr_rec_period} ind_marked_bad_chans]);
% if HAPPE is selected, run wICA on file
if grp_proc_info_in.beapp_ica_type == 2
EEG_tmp = happe_run_wICA_on_file(EEG_tmp, file_proc_info.beapp_srate, grp_proc_info_in.happe_plotting_on);
end
% run ICA to evaluate components this time
EEG_after_ICA = pop_runica(EEG_tmp, 'extended',1,'interupt','on','verbose', 'off');
if (grp_proc_info_in.beapp_ica_type == 1) || (grp_proc_info_in.beapp_ica_type == 2)
%use MARA to flag artifactual IComponents automatically if artifact probability > .5
[EEG_out,ica_report_struct,skip_file] = beapp_ica_run_mara (EEG_after_ICA,file_proc_info.beapp_fname{1},grp_proc_info_in.happe_plotting_on,ica_report_struct,curr_rec_period);
% skip recording period if all components rejected
if skip_file, continue; end;
else
EEG_out = EEG_after_ICA;
icaweights = EEG_out.icaweights;
icasphere = EEG_out.icasphere;
end
diary on;
if grp_proc_info_in.beapp_ica_type == 2
if ~grp_proc_info_in.beapp_rmv_bad_chan_on
%interpolate channels marked bad above, reference data
EEG_out = pop_interp(EEG_out, full_selected_channels, 'spherical');
end
EEG_out = pop_reref(EEG_out, [], 'exclude', ind_marked_bad_chans);
end
eeg{curr_rec_period} = NaN(size(eeg{curr_rec_period}));
[~,~,inds_in_dict]=intersect({EEG_out.chanlocs.labels},chan_name_indx_dict(:,1),'stable');
eeg{curr_rec_period}(cell2mat(chan_name_indx_dict(inds_in_dict,2)),:) = EEG_out.data;
clear chan_name_indx_dict
end
file_ica_toc = toc;
file_proc_info.ica_stats.Time_Elapsed_For_File = {num2str(file_ica_toc/60)};
if grp_proc_info_in.beapp_toggle_mods{'ica','Module_Xls_Out_On'}
ICA_report_table.Num_Rec_Periods(curr_file) = num2cell(curr_rec_period);
ICA_report_table.File_Rec_Period_Lengths_In_Secs(curr_file) = {ica_report_struct.rec_period_lengths_in_secs};
ICA_report_table.Number_Channels_UserSelected(curr_file) = {length(chan_IDs)};
ICA_report_table.Number_Good_Channels_Selected_Per_Rec_Period(curr_file) = {ica_report_struct.good_chans_per_rec_period};
if ~all(cellfun(@isempty,file_proc_info.beapp_bad_chans))
tmp = cellfun(@mat2str,file_proc_info.beapp_bad_chans, 'UniformOutput',0);
ICA_report_table.Interpolated_Channel_IDs_Per_Rec_Period(curr_file) =tmp;
else
ICA_report_table.Interpolated_Channel_IDs_Per_Rec_Period(curr_file) ={''};
end
if ~(grp_proc_info_in.beapp_ica_type ==3)
ICA_report_table.Percent_ICs_Rejected_Per_Rec_Period(curr_file) = {ica_report_struct.percent_ICs_rej_per_rec_period};
ICA_report_table.Percent_Variance_Kept_of_Data_Input_to_MARA_Per_Rec_Period(curr_file) = {ica_report_struct.perc_var_post_wave_per_rec_period};
ICA_report_table.Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period(curr_file) = {ica_report_struct.mn_art_prob_per_rec_period};
ICA_report_table.Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period(curr_file) = {ica_report_struct.median_art_prob_per_rec_period};
end
ICA_report_table.Time_Elapsed_For_File(curr_file) = {num2str(file_ica_toc/60)};
end
file_proc_info.ica_stats.Number_Good_Channels_Selected_Per_Rec_Period = {ica_report_struct.good_chans_per_rec_period};
if ~(grp_proc_info_in.beapp_ica_type ==3)
file_proc_info.ica_stats.Percent_ICs_Rejected_Per_Rec_Period = {ica_report_struct.percent_ICs_rej_per_rec_period};
file_proc_info.ica_stats.Percent_Variance_Kept_of_Data_Input_to_MARA_Per_Rec_Period = {ica_report_struct.perc_var_post_wave_per_rec_period};
file_proc_info.ica_stats.Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period = {ica_report_struct.mn_art_prob_per_rec_period};
file_proc_info.ica_stats.Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period = {ica_report_struct.median_art_prob_per_rec_period};
end
if ~all(cellfun(@isempty,eeg))
file_proc_info = beapp_prepare_to_save_file('ica',file_proc_info, grp_proc_info_in, src_dir{1});
if grp_proc_info_in.beapp_ica_type ==3
save(file_proc_info.beapp_fname{1},'eeg','file_proc_info','icaweights','icasphere');
else
save(file_proc_info.beapp_fname{1},'eeg','file_proc_info');
end
%pop_saveset(EEG_out,[strrep(file_proc_info.beapp_fname{1},'mat','') '_post_ICA']);
end
clearvars -except grp_proc_info_in curr_file src_dir ICA_report_table cleanline_path ica_report_struct
end
end
% save report if user selected option
cd (grp_proc_info_in.beapp_genout_dir{1})
if grp_proc_info_in.beapp_toggle_mods{'ica','Module_Xls_Out_On'}
writetable(ICA_report_table, ['ICA_Report_Table ',grp_proc_info_in.beapp_curr_run_tag,'.csv']);
end
% remove cleanline path
rmpath(genpath(cleanline_path));
|
github
|
lcnbeapp/beapp-master
|
h_epoch_interp_spl.m
|
.m
|
beapp-master/functions/h_epoch_interp_spl.m
| 5,579 |
utf_8
|
b3f72af0ca562a5a7d2b9cd9eca573ff
|
% Edit to the EEGLAB interpolation function to interpolate different
% channels within each epoch
% Cleaned up and removed irrelevant sections.
%
% Additions Copyright (C) 2010 Hugh Nolan, Robert Whelan and Richard Reilly, Trinity College Dublin,
% Ireland
%
% Based on:
%
% eeg_interp() - interpolate data channels
%
% Usage: EEGOUT = eeg_interp(EEG, badchans, method);
%
% Inputs:
% EEG - EEGLAB dataset
% badchans - [integer array] indices of channels to interpolate.
% For instance, these channels might be bad.
% [chanlocs structure] channel location structure containing
% either locations of channels to interpolate or a full
% channel structure (missing channels in the current
% dataset are interpolated).
% method - [string] method used for interpolation (default is 'spherical').
% 'invdist' uses inverse distance on the scalp
% 'spherical' uses superfast spherical interpolation.
% 'spacetime' uses griddata3 to interpolate both in space
% and time (very slow and cannot be interupted).
% Output:
% EEGOUT - data set with bad electrode data replaced by
% interpolated data
%
% Author: Arnaud Delorme, CERCO, CNRS, Mai 2006-
% Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected]
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Log: eeg_interp.m,v $
% Revision 1.7 2009/08/05 03:20:42 arno
% new interpolation function
%
% Revision 1.6 2009/07/30 03:32:47 arno
% fixed interpolating bad channels
%
% Revision 1.5 2009/07/02 19:30:33 arno
% fix problem with empty channel
%
% Revision 1.4 2009/07/02 18:23:33 arno
% fixing interpolation
%
% Revision 1.3 2009/04/21 21:48:53 arno
% make default spherical in eeg_interp
%
% Revision 1.2 2008/04/16 17:34:45 arno
% added spherical and 3-D interpolation
%
% Revision 1.1 2006/09/12 18:46:30 arno
% Initial revision
%
function EEG = h_epoch_interp_spl(EEG, bad_elec_epochs, ignore_chans)
warning off;
if nargin < 2
help eeg_interp;
return;
end;
if isempty(bad_elec_epochs) || ~iscell(bad_elec_epochs)
fprintf('Incorrect input format.\n');
return;
end
if ~exist('ignore_chans','var')
ignore_chans=[];
end
for v=1:length(bad_elec_epochs)
if ~isempty(bad_elec_epochs{v})
badchans = bad_elec_epochs{v};
goodchans = setdiff(1:size(EEG.data,1), badchans);
goodchans = setdiff(goodchans, ignore_chans);
% find non-empty good channels
% ----------------------------
nonemptychans = find(~cellfun('isempty', { EEG.chanlocs.theta }));
goodchans = intersect(goodchans,nonemptychans);
badchans = intersect(badchans, nonemptychans);
% scan data points
% ----------------
% get theta, rad of electrodes
% ----------------------------
xelec = [ EEG.chanlocs(goodchans).X ];
yelec = [ EEG.chanlocs(goodchans).Y ];
zelec = [ EEG.chanlocs(goodchans).Z ];
rad = sqrt(xelec.^2+yelec.^2+zelec.^2);
xelec = xelec./rad;
yelec = yelec./rad;
zelec = zelec./rad;
xbad = [ EEG.chanlocs(badchans).X ];
ybad = [ EEG.chanlocs(badchans).Y ];
zbad = [ EEG.chanlocs(badchans).Z ];
rad = sqrt(xbad.^2+ybad.^2+zbad.^2);
xbad = xbad./rad;
ybad = ybad./rad;
zbad = zbad./rad;
EEG.data(badchans,:,v) = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(goodchans,:,v));
end
end
EEG = eeg_checkset(EEG);
warning on;
function allres = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, values)
newchans = length(xbad);
numpoints = size(values,2);
Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec);
Gsph = computeg(xbad,ybad,zbad,xelec,yelec,zelec);
% compute solution for parameters C
% ---------------------------------
meanvalues = mean(values);
values = values - repmat(meanvalues, [size(values,1) 1]); % make mean zero
values = [values;zeros(1,numpoints)];
C = pinv([Gelec;ones(1,length(Gelec))]) * values;
clear values;
allres = zeros(newchans, numpoints);
% apply results
% -------------
for j = 1:size(Gsph,1)
allres(j,:) = sum(C .* repmat(Gsph(j,:)', [1 size(C,2)]));
end
allres = allres + repmat(meanvalues, [size(allres,1) 1]);
% compute G function
% ------------------
function g = computeg(x,y,z,xelec,yelec,zelec)
unitmat = ones(length(x(:)),length(xelec));
EI = unitmat - sqrt((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +...
(repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +...
(repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2);
g = zeros(length(x(:)),length(xelec));
%dsafds
m = 4; % 3 is linear, 4 is best according to Perrin's curve
for n = 1:7
L = legendre(n,EI);
g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:));
end
g = g/(4*pi);
|
github
|
lcnbeapp/beapp-master
|
batch_edf2beapp.m
|
.m
|
beapp-master/functions/batch_edf2beapp.m
| 2,347 |
utf_8
|
8bebbf251ff7cea3a0bb00618268507b
|
% this function is entirely adapted from the Biosig toolbox for EEGLAB
% and from the following functions:
% pop_readedf() - Read a European data format .EDF data file.
% Author: Arnaud Delorme, CNL / Salk Institute, 13 March 2002
%
% pop_readbdf() - Read Biosemi 24-bit BDF file
% Author: Arnaud Delorme, CNL / Salk Institute, 13 March 2002
function grp_proc_info_in = batch_edf2beapp(grp_proc_info_in)
cd(grp_proc_info_in.src_dir{1});
flist = dir('*.edf');
grp_proc_info_in.src_fname_all = {flist.name};
for curr_file = 1:length(flist)
fprintf('Reading EDF format using BIOSIG...\n');
EDF = sopen(grp_proc_info_in.src_fname_all{curr_file}, 'r');
[tmpdata EDF] = sread(EDF, Inf); tmpdata = tmpdata';
eeg{1} = tmpdata;
% save source file variables
file_proc_info.src_fname=grp_proc_info_in.src_fname_all(curr_file);
file_proc_info.src_srate=grp_proc_info_in.src_srate_all(curr_file);
file_proc_info.src_nchan=size(eeg{1},1);
file_proc_info.src_epoch_nsamps(1)=size(eeg{1},2);
file_proc_info.src_num_epochs = 1;
file_proc_info.src_linenoise = grp_proc_info_in.src_linenoise_all(curr_file);
file_proc_info.epoch_inds_to_process = [1]; % assumes mat files only have one recording period
% save starting beapp file variables from source information
file_proc_info.beapp_fname=grp_proc_info_in.beapp_fname_all(curr_file);
file_proc_info.beapp_srate=file_proc_info.src_srate;
file_proc_info.beapp_bad_chans ={[]};
file_proc_info.beapp_nchans_used=[file_proc_info.src_nchan];
file_proc_info.beapp_indx={1:size(eeg{1},1)}; % indices for electrodes being used for analysis at current time
file_proc_info.beapp_num_epochs = 1; % assumes mat files only have one recording period
%[EEG.data, header] = readedf(filename);
EEG.nbchan = size(EEG.data,1);
EEG.pnts = size(EEG.data,2);
EEG.trials = 1;
EEG.srate = EDF.SampleRate(1);
EEG.setname = 'EDF file';
disp('Event information might be encoded in the last channel');
disp('To extract these events, use menu File > Import event info > From data channel');
EEG.filename = filename;
EEG.filepath = '';
EEG.xmin = 0;
EEG.chanlocs = struct('labels', cellstr(EDF.Label));
end
|
github
|
lcnbeapp/beapp-master
|
read_mff_data_blocks.m
|
.m
|
beapp-master/functions/read_mff_data_blocks.m
| 549 |
utf_8
|
94b05f952f57bd5e1df7d8c8c662d0ab
|
% Original function written by Colin Davey for EGI API
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
function data = read_mff_data_blocks(binObj, blocks, beginBlock, endBlock)
for blockInd = beginBlock-1:endBlock-1
tmpdata = read_mff_data_block(binObj, blocks, blockInd);
if blockInd == beginBlock-1
data = tmpdata;
else
if size(data,1) == size(tmpdata,1)
data = [data tmpdata];
else
% Error: blocks disagree on number of channels
end
end
end
end
|
github
|
lcnbeapp/beapp-master
|
beapp_ica_select_channels_for_file.m
|
.m
|
beapp-master/functions/beapp_ica_select_channels_for_file.m
| 5,429 |
utf_8
|
817deda80d2bb515b0ea4990c54dca63
|
%% beapp_ica_select_channels_for_file
%
% select channels to use in ICA module. By default, uses 10-20 for net+
% user set additional channels (because of MARA).In the future, users not running MARA
% will be able to choose any channels they'd like
%
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% The Batch Electroencephalography Automated Processing Platform (BEAPP)
% Copyright (C) 2015, 2016, 2017
% Authors: AR Levin, AS Méndez Leal, LJ Gabard-Durnam, HM O'Leary
%
% This software is being distributed with the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU General
% Public License for more details.
%
% In no event shall Boston Children’s Hospital (BCH), the BCH Department of
% Neurology, the Laboratories of Cognitive Neuroscience (LCN), or software
% contributors to BEAPP be liable to any party for direct, indirect,
% special, incidental, or consequential damages, including lost profits,
% arising out of the use of this software and its documentation, even if
% Boston Children’s Hospital,the Laboratories of Cognitive Neuroscience,
% and software contributors have been advised of the possibility of such
% damage. Software and documentation is provided “as is.” Boston Children’s
% Hospital, the Laboratories of Cognitive Neuroscience, and software
% contributors are under no obligation to provide maintenance, support,
% updates, enhancements, or modifications.
%
% This program is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License (version 3) as
% published by the Free Software Foundation.
%
% You should receive a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function [chan_IDs, file_proc_info] = beapp_ica_select_channels_for_file (file_proc_info,src_unique_nets, happe_additional_chans_lbls,name_10_20_elecs,chans_to_exclude,use_all_10_20,ica_10_20_chans2use,name_selected_10_20_elecs)
% get 10-20 labels and additional user set channels for this net
uniq_net_ind = find(strcmp(src_unique_nets, file_proc_info.net_typ{1}));
if use_all_10_20 == 1
%overlap_10_20_and_additional_chans = intersect({file_proc_info.net_vstruct(file_proc_info.net_10_20_elecs).labels},happe_additional_chans_lbls{uniq_net_ind},'stable');
overlap_10_20_and_additional_chans = intersect({file_proc_info.net_vstruct(file_proc_info.net_10_20_elecs).labels},happe_additional_chans_lbls,'stable');
% remove additional channels already included in 10-20s
if ~isempty(overlap_10_20_and_additional_chans)
file_proc_info.net_happe_additional_chans_lbls =setdiff(happe_additional_chans_lbls,{file_proc_info.net_vstruct(file_proc_info.net_10_20_elecs).labels},'stable');
else
%file_proc_info.net_happe_additional_chans_lbls = happe_additional_chans_lbls{uniq_net_ind};
file_proc_info.net_happe_additional_chans_lbls = happe_additional_chans_lbls;
end
else
overlap_10_20_and_additional_chans = intersect({file_proc_info.net_vstruct(ica_10_20_chans2use{uniq_net_ind}).labels},happe_additional_chans_lbls,'stable');
% remove additional channels already included in 10-20s
if ~isempty(overlap_10_20_and_additional_chans)
file_proc_info.net_happe_additional_chans_lbls =setdiff(happe_additional_chans_lbls,{file_proc_info.net_vstruct(ica_10_20_chans2use{uniq_net_ind}).labels},'stable');
else
%file_proc_info.net_happe_additional_chans_lbls = happe_additional_chans_lbls{uniq_net_ind};
file_proc_info.net_happe_additional_chans_lbls = happe_additional_chans_lbls;
end
end
[file_proc_info.net_vstruct(file_proc_info.net_10_20_elecs(~isnan(file_proc_info.net_10_20_elecs))).labels] = name_selected_10_20_elecs{uniq_net_ind}{:};
if ~all(cellfun(@isempty,chans_to_exclude))
lbls_chans_to_exclude_this_net = {file_proc_info.net_vstruct(chans_to_exclude{uniq_net_ind}).labels};
else
lbls_chans_to_exclude_this_net ={};
end
if use_all_10_20 == 1
% check if user added optional channels,and only use electrodes that have labels in the dataset
if (length(file_proc_info.net_happe_additional_chans_lbls) == 1) && isempty(file_proc_info.net_happe_additional_chans_lbls{1})
chan_IDs = unique(name_10_20_elecs);
else
chan_IDs_all = unique([name_10_20_elecs file_proc_info.net_happe_additional_chans_lbls]);
% select desired channels listed in this net
chan_IDs = intersect(chan_IDs_all,{file_proc_info.net_vstruct.labels},'stable');
if length(chan_IDs) < length(chan_IDs_all)
extra_elecs = setdiff(chan_IDs_all,chan_IDs,'stable');
warning (['Electrode(s) ' sprintf('%s ,',extra_elecs{1:end-1}) extra_elecs{end} ' are not found in file chanlocs ']);
end
% exclude channels if set by user
chan_IDs = setdiff(chan_IDs,lbls_chans_to_exclude_this_net,'stable');
end
else
if isempty(file_proc_info.net_happe_additional_chans_lbls)
chan_IDs = ({file_proc_info.net_vstruct(ica_10_20_chans2use{uniq_net_ind}).labels});
else
chan_IDs = ({file_proc_info.net_vstruct(ica_10_20_chans2use{uniq_net_ind}).labels file_proc_info.net_happe_additional_chans_lbl{uniq_net_ind}});
end
end
|
github
|
lcnbeapp/beapp-master
|
align_segment_info_across_src_files.m
|
.m
|
beapp-master/functions/align_segment_info_across_src_files.m
| 582 |
utf_8
|
66dd4c2ee1e5d0a0eded65c240211ea8
|
%% this functionality is not yet supported and should not be used by most users
% will eventually align segment information from hand edited files that are
% exported as segments with continuous recordings
function eeg_w = align_segment_info_across_src_files (eeg,file_proc_info_in,seg_info_dir)
subID = strsplit(file_proc_info_in.beapp_fname{1},'.');
subID = subID{1};
cd(seg_info_dir)
seg_flist = dir('*.mat');
seg_flist = {seg_flist.name};
file_inda = strfind(seg_flist,subID);
file_ind = find(not(cellfun('isempty', file_inda)));
load(seg_flist{file_ind});
|
github
|
lcnbeapp/beapp-master
|
byc_plot_table.m
|
.m
|
beapp-master/functions/byc_plot_table.m
| 4,131 |
utf_8
|
3613f83833c88d5fce502f2b7dddef84
|
%% this script plots some of the features reported in the table
function byc_plot_table(signal,signal_low_mat,result_table,time_s,byc_dir,filename,chan,seg,save_reports)
% clear
% close all
% clc
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
cd ..
%data_result_folder='C:\Users\ch203202\Downloads\bycycle_matlab-master\Results\Results_mat\';
%fig_folder='C:\Users\ch203202\Downloads\bycycle_matlab-master\Results\Results_fig\';
%load([data_result_folder 'results'])
%% plot signal and BP signal
% figure
% plot(time_s,signal)
% hold on
% plot(time_s,signal_low_mat)
% legend({'signal','BP signal'})
% title(['signal and BP signal [' num2str(frequency_limits) '] Hz'])
% xlabel('Time [s]')
% savefig([fig_folder 'signal_band_pass'])
%% showing peaks and other cycle markers
figure
h(1)=subplot(5,1,1);
plot(time_s , signal_low_mat)
hold on
plot( time_s(result_table.sample_peak+1) , signal_low_mat(result_table.sample_peak+1),'bx')
plot( time_s(result_table.sample_last_trough+1) , signal_low_mat(result_table.sample_last_trough+1),'rx')
plot( time_s(result_table.sample_zerox_decay+1) , signal_low_mat(result_table.sample_zerox_decay+1),'mx')
plot( time_s(result_table.sample_zerox_rise+1) , signal_low_mat(result_table.sample_zerox_rise+1),'gx')
legend({'BP signal','sample peak','sample through','mid decay','mid rise'})
title('BP signal and peaks, valleys, decays and rise')
xlabel('Time [s]')
h(2)=subplot(5,1,2);
plot( time_s(result_table.sample_peak+1) , result_table.amp_consistency,'b')
title('amp consistency')
h(3)=subplot(5,1,3);
plot( time_s(result_table.sample_peak+1) , result_table.amp_fraction,'b')
title('amp fraction')
h(4)=subplot(5,1,4);
plot( time_s(result_table.sample_peak+1) , result_table.period_consistency,'b')
title('period consistency')
h(5)=subplot(5,1,5);
plot( time_s(result_table.sample_peak+1) , result_table.monotonicity,'b')
title('monotonicity')
linkaxes(h,'x')
pause(.5)
if save_reports
src_dir{1} = pwd;
cd(byc_dir);
mkdir(strcat(filename,'_Image_outputs'));
cd(strcat(filename,'_Image_outputs'));
savefig([filename '_Channel' chan '_Segment',seg,'TimeSeries.fig'])
cd(src_dir{1});
end
% savefig([fig_folder 'band_pass_peaks'])
%% showing comparison between times
% figure
% subplot(3,1,1);
% plot(result_table.time_trough./fs_mat,result_table.time_peak./fs_mat,'b.')
% max_x_y=max(max(result_table.time_trough,result_table.time_peak))./fs_mat;
% hold on
% plot([0 max_x_y],[0 max_x_y],'r')
% xlim([0 max_x_y*1.1])
% ylim([0 max_x_y*1.1])
% % axis square
% ylabel('time peak [s]')
% xlabel('time through [s]')
% title('time through vs peak')
%
% subplot(3,1,2)
% plot(result_table.time_trough./fs_mat,result_table.time_rise./fs_mat,'b.')
% max_x_y=max(max(result_table.time_trough,result_table.time_rise))./fs_mat;
% hold on
% plot([0 max_x_y],[0 max_x_y],'r')
% xlim([0 max_x_y*1.1])
% ylim([0 max_x_y*1.1])
% % axis square
% ylabel('time rise [s]')
% xlabel('time through [s]')
% title('time through vs rise')
%
% subplot(3,1,3)
% plot(result_table.time_ptsym,result_table.time_rdsym,'b.')
% max_x_y=max(max(result_table.time_ptsym,result_table.time_rdsym));
% hold on
% plot([0 max_x_y],[0 max_x_y],'r')
% xlim([0 max_x_y*1.1])
% ylim([0 max_x_y*1.1])
% % axis square
% ylabel('time ptsym ')
% xlabel('time rdsym')
% title('time ptsym vs rdsym')
% savefig([fig_folder 'time_peaks'])
%% showing burst-related parameters
figure
h_hist(1)=subplot(2,2,1);
histogram(result_table.amp_consistency,'normalization','probability')
title('amp consistency')
h_hist(2)=subplot(2,2,2);
histogram(result_table.amp_fraction,'normalization','probability')
title('amp fraction')
h_hist(3)=subplot(2,2,3);
histogram(result_table.period_consistency,'normalization','probability')
title('period consistency')
h_hist(4)=subplot(2,2,4);
histogram(result_table.monotonicity,'normalization','probability')
title('monotonicity')
pause(.5)
if save_reports
cd(byc_dir);
cd(strcat(filename,'_Image_outputs'));
savefig([filename '_Channel' chan '_Segment',seg,'Histograms.fig'])
cd(src_dir{1});
end
|
github
|
lcnbeapp/beapp-master
|
beapp_eeglab_path_adding.m
|
.m
|
beapp-master/functions/beapp_eeglab_path_adding.m
| 26,051 |
utf_8
|
abc4e9f1770eefbff8aeb52c5bad0ca8
|
% this script calls the path initializing EEGLab code, a subset of
% the primary eeglab script
% this is done to prevent errors caused by adding EEGLab/plugin subfolders
% to the path
%
% EEGLAB is a Matlab graphic user interface environment for
% electrophysiological data analysis incorporating the ICA/EEG toolbox
% (Makeig et al.) developed at CNL / The Salk Institute, 1997-2001.
% Released 11/2002- as EEGLAB (Delorme, Makeig, et al.) at the Swartz Center
% for Computational Neuroscience, Institute for Neural Computation,
% University of California San Diego (http://sccn.ucsd.edu/).
% User feedback welcome: email [email protected]
%
% Authors: Arnaud Delorme and Scott Makeig, with substantial contributions
% from Colin Humphries, Sigurd Enghoff, Tzyy-Ping Jung, plus
% contributions
% from Tony Bell, Te-Won Lee, Luca Finelli and many other contributors.
%
function beapp_eeglab_path_adding
if nargout > 0
varargout = { [] [] 0 {} [] };
%[ALLEEG, EEG, CURRENTSET, ALLCOM]
end;
% check Matlab version
% --------------------
vers = version;
tmpv = which('version');
if ~isempty(findstr(lower(tmpv), 'biosig'))
[tmpp tmp] = fileparts(tmpv);
rmpath(tmpp);
end;
% remove freemat folder if it exist
tmpPath = fileparts(fileparts(which('sread')));
newPath = fullfile(tmpPath, 'maybe-missing', 'freemat3.5');
if exist(newPath) == 7
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpath(newPath)
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
if str2num(vers(1)) < 7 && str2num(vers(1)) >= 5
tmpWarning = warning('backtrace');
warning backtrace off;
warning('You are using a Matlab version older than 7.0');
warning('This Matlab version is too old to run the current EEGLAB');
warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip');
warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3');
warning(tmpWarning);
return;
end;
% check Matlab version
% --------------------
vers = version;
indp = find(vers == '.');
if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end;
indp = find(vers == '.');
vers = str2num(vers(1:indp(2)-1));
if vers < 7.06
tmpWarning = warning('backtrace');
warning backtrace off;
warning('You are using a Matlab version older than 7.6 (2008a)');
warning('Some of the EEGLAB functions might not be functional');
warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip');
warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3');
warning(tmpWarning);
end;
% check for duplicate versions of EEGLAB
% --------------------------------------
eeglabpath = mywhich('eeglab.m');
eeglabpath = eeglabpath(1:end-length('eeglab.m'));
if nargin < 1
eeglabpath2 = '';
if strcmpi(eeglabpath, pwd) || strcmpi(eeglabpath(1:end-1), pwd)
cd('functions');
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpath(eeglabpath);
warning('on', 'MATLAB:rmpath:DirNotFound');
eeglabpath2 = mywhich('eeglab.m');
cd('..');
else
try, rmpath(eeglabpath); catch, end;
eeglabpath2 = mywhich('eeglab.m');
end;
if ~isempty(eeglabpath2)
%evalin('base', 'clear classes updater;'); % this clears all the variables
eeglabpath2 = eeglabpath2(1:end-length('eeglab.m'));
tmpWarning = warning('backtrace');
warning backtrace off;
disp('******************************************************');
warning('There are at least two versions of EEGLAB in your path');
warning(sprintf('One is at %s', eeglabpath));
warning(sprintf('The other one is at %s', eeglabpath2));
warning(tmpWarning);
end;
addpath(eeglabpath);
end;
% add the paths
% -------------
if strcmpi(eeglabpath, './') || strcmpi(eeglabpath, '.\'), eeglabpath = [ pwd filesep ]; end;
% solve BIOSIG problem
% --------------------
pathtmp = mywhich('wilcoxon_test');
if ~isempty(pathtmp)
try,
rmpath(pathtmp(1:end-15));
catch, end;
end;
% test for local SCCN copy
% ------------------------
if ~iseeglabdeployed2
addpathifnotinlist(eeglabpath);
if exist( fullfile( eeglabpath, 'functions', 'adminfunc') ) ~= 7
warning('EEGLAB subfolders not found');
end;
end;
% determine file format
% ---------------------
fileformat = 'maclinux';
comp = computer;
try
if strcmpi(comp(1:3), 'GLN') | strcmpi(comp(1:3), 'MAC') | strcmpi(comp(1:3), 'SOL')
fileformat = 'maclinux';
elseif strcmpi(comp(1:5), 'pcwin')
fileformat = 'pcwin';
end;
end;
% add paths
% ---------
if ~iseeglabdeployed2
tmp = which('eeglab_data.set');
if ~isempty(which('eeglab_data.set')) && ~isempty(which('GSN-HydroCel-32.sfp'))
warning backtrace off;
warning(sprintf([ '\n\nPath Warning: It appears that you have added the path to all of the\n' ...
'subfolders to EEGLAB. This may create issues with some EEGLAB extensions\n' ...
'If EEGLAB cannot start or your experience a large number of warning\n' ...
'messages, remove all the EEGLAB paths then go to the EEGLAB folder\n' ...
'and start EEGLAB which will add all the necessary paths.\n\n' ]));
warning backtrace on;
foldertorm = fileparts(which('fgetl.m'));
if ~isempty(strfind(foldertorm, 'eeglab'))
rmpath(foldertorm);
end;
foldertorm = fileparts(which('strjoin.m'));
if ~isempty(strfind(foldertorm, 'eeglab'))
rmpath(foldertorm);
end;
end;
myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]);
myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]);
myaddpath( eeglabpath, ['@mmo' filesep 'mmo.m'], 'functions');
myaddpath( eeglabpath, 'readeetraklocs.m', [ 'functions' filesep 'sigprocfunc' ]);
myaddpath( eeglabpath, 'supergui.m', [ 'functions' filesep 'guifunc' ]);
myaddpath( eeglabpath, 'pop_study.m', [ 'functions' filesep 'studyfunc' ]);
myaddpath( eeglabpath, 'pop_loadbci.m', [ 'functions' filesep 'popfunc' ]);
myaddpath( eeglabpath, 'statcond.m', [ 'functions' filesep 'statistics' ]);
myaddpath( eeglabpath, 'timefreq.m', [ 'functions' filesep 'timefreqfunc' ]);
myaddpath( eeglabpath, 'icademo.m', [ 'functions' filesep 'miscfunc' ]);
myaddpath( eeglabpath, 'eeglab1020.ced', [ 'functions' filesep 'resources' ]);
myaddpath( eeglabpath, 'startpane.m', [ 'functions' filesep 'javachatfunc' ]);
addpathifnotinlist(fullfile(eeglabpath, 'plugins'));
eeglab_options;
% remove path to to fmrlab if neceecessary
path_runica = fileparts(mywhich('runica'));
if length(path_runica) > 6 && strcmpi(path_runica(end-5:end), 'fmrlab')
rmpath(path_runica);
end;
% add path if toolboxes are missing
% ---------------------------------
signalpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'signal');
optimpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'optim');
if option_donotusetoolboxes
p1 = fileparts(mywhich('ttest'));
p2 = fileparts(mywhich('filtfilt'));
p3 = fileparts(mywhich('optimtool'));
p4 = fileparts(mywhich('gray2ind'));
if ~isempty(p1), rmpath(p1); end;
if ~isempty(p2), rmpath(p2); end;
if ~isempty(p3), rmpath(p3); end;
if ~isempty(p4), rmpath(p4); end;
end;
if ~license('test','signal_toolbox') || exist('pwelch') ~= 2
warning('off', 'MATLAB:dispatcher:nameConflict');
addpath( signalpath );
else
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpathifpresent( signalpath );
rmpathifpresent(optimpath);
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
if ~license('test','optim_toolbox') && ~ismatlab
addpath( optimpath );
else
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpathifpresent( optimpath );
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
% remove BIOSIG path which are not needed and might cause conflicts
biosigp{1} = fileparts(which('sopen.m'));
biosigp{2} = fileparts(which('regress_eog.m'));
biosigp{3} = fileparts(which('DecimalFactors.txt'));
removepath(fileparts(fileparts(biosigp{1})), biosigp{:})
else
eeglab_options;
end;
% for the history function
% ------------------------
comtmp = 'warning off MATLAB:mir_warning_variable_used_as_function';
if nargin < 1 | exist('EEG') ~= 1
clear global EEG ALLEEG CURRENTSET ALLCOM LASTCOM STUDY;
CURRENTSTUDY = 0;
EEG = eeg_emptyset;
eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;');
if ismatlab && get(0, 'screendepth') <= 8
disp('Warning: screen color depth too low, some colors will be inaccurate in time-frequency plots');
end;
end;
if nargin == 1
if strcmp(onearg, 'versions')
disp( [ 'EEGLAB v' eeg_getversion ] );
elseif strcmp(onearg, 'nogui')
if nargout < 1, clear ALLEEG; end; % do not return output var
return;
elseif strcmp(onearg, 'redraw')
if ~ismatlab,return; end;
W_MAIN = findobj('tag', 'EEGLAB');
if ~isempty(W_MAIN)
updatemenu;
if nargout < 1, clear ALLEEG; end; % do not return output var
return;
else
eegh('eeglab(''redraw'');');
end;
elseif strcmp(onearg, 'rebuild')
if ~ismatlab,return; end;
W_MAIN = findobj('tag', 'EEGLAB');
close(W_MAIN);
eeglab;
return;
else
fprintf(2,['EEGLAB Warning: Invalid argument ''' onearg '''. Restarting EEGLAB interface instead.\n']);
eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab(''rebuild'');');
end;
else
onearg = 'rebuild';
end;
% default option folder
% ---------------------
if ~iseeglabdeployed2
eeglab_options;
%fprintf('eeglab: options file is %s%seeg_options.m\n', homefolder, filesep);
end;
% checking strings
% ----------------
e_try = 'try,';
e_catch = 'catch, eeglab_error; LASTCOM= ''''; clear EEGTMP ALLEEGTMP STUDYTMP; end;';
nocheck = e_try;
ret = 'if ~isempty(LASTCOM), if LASTCOM(1) == -1, LASTCOM = ''''; return; end; end;';
check = ['[EEG LASTCOM] = eeg_checkset(EEG, ''data'');' ret ' eegh(LASTCOM);' e_try];
checkcont = ['[EEG LASTCOM] = eeg_checkset(EEG, ''contdata'');' ret ' eegh(LASTCOM);' e_try];
checkica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'');' ret ' eegh(LASTCOM);' e_try];
checkepoch = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'');' ret ' eegh(LASTCOM);' e_try];
checkevent = ['[EEG LASTCOM] = eeg_checkset(EEG, ''event'');' ret ' eegh(LASTCOM);' e_try];
checkbesa = ['[EEG LASTCOM] = eeg_checkset(EEG, ''besa'');' ret ' eegh(''% no history yet for BESA dipole localization'');' e_try];
checkepochica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'');' ret ' eegh(LASTCOM);' e_try];
checkplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkepochplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkepochicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
% check string and backup old dataset
% -----------------------------------
backup = [ 'if CURRENTSET ~= 0,' ...
' [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, CURRENTSET, ''savegui'');' ...
' eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET, ''''savedata'''');'');' ...
'end;' ];
storecall = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);'');';
storenewcall = '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM);';
storeallcall = [ 'if ~isempty(ALLEEG) & ~isempty(ALLEEG(1).data), ALLEEG = eeg_checkset(ALLEEG);' ...
'EEG = eeg_retrieve(ALLEEG, CURRENTSET); eegh(''ALLEEG = eeg_checkset(ALLEEG); EEG = eeg_retrieve(ALLEEG, CURRENTSET);''); end;' ];
testeegtmp = 'if exist(''EEGTMP'') == 1, EEG = EEGTMP; clear EEGTMP; end;'; % for backward compatibility
ifeeg = 'if ~isempty(LASTCOM) & ~isempty(EEG),';
ifeegnh = 'if ~isempty(LASTCOM) & ~isempty(EEG) & ~isempty(findstr(''='',LASTCOM)),';
% nh = no dataset history
% -----------------------
e_storeall_nh = [e_catch 'eegh(LASTCOM);' ifeeg storeallcall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_hist_nh = [e_catch 'eegh(LASTCOM);'];
% same as above but also save history in dataset
% ----------------------------------------------
e_newset = [e_catch 'EEG = eegh(LASTCOM, EEG);' testeegtmp ifeeg storenewcall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_store = [e_catch 'EEG = eegh(LASTCOM, EEG);' ifeegnh storecall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_hist = [e_catch 'EEG = eegh(LASTCOM, EEG);'];
e_histdone = [e_catch 'EEG = eegh(LASTCOM, EEG); if ~isempty(LASTCOM), disp(''Done.''); end;' ];
% study checking
% --------------
e_load_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); ALLEEG = ALLEEGTMP; EEG = ALLEEG; CURRENTSET = [1:length(EEG)]; eegh(''CURRENTSTUDY = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];''); CURRENTSTUDY = 1; disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');'];
e_plot_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; % ALLEEG not modified
% build structures for plugins
% ----------------------------
trystrs.no_check = e_try;
trystrs.check_data = check;
trystrs.check_ica = checkica;
trystrs.check_cont = checkcont;
trystrs.check_epoch = checkepoch;
trystrs.check_event = checkevent;
trystrs.check_epoch_ica = checkepochica;
trystrs.check_chanlocs = checkplot;
trystrs.check_epoch_chanlocs = checkepochplot;
trystrs.check_epoch_ica_chanlocs = checkepochicaplot;
catchstrs.add_to_hist = e_hist;
catchstrs.store_and_hist = e_store;
catchstrs.new_and_hist = e_newset;
catchstrs.new_non_empty = e_newset;
catchstrs.update_study = e_plot_study;
% detecting icalab
% ----------------
if exist('icalab')
disp('ICALAB toolbox detected (algo. added to "run ICA" interface)');
end;
if ~iseeglabdeployed2
% check for older version of Fieldtrip and presence of topoplot
% -------------------------------------------------------------
if ismatlab
ptopoplot = fileparts(mywhich('cbar'));
ptopoplot2 = fileparts(mywhich('topoplot'));
if ~strcmpi(ptopoplot, ptopoplot2),
%disp(' Warning: duplicate function topoplot.m in Fieldtrip and EEGLAB');
%disp(' EEGLAB function will prevail and call the Fieldtrip one when appropriate');
addpath(ptopoplot);
end;
end;
end;
if iseeglabdeployed2
disp('Adding FIELDTRIP toolbox functions');
disp('Adding BIOSIG toolbox functions');
disp('Adding FILE-IO toolbox functions');
funcname = { 'eegplugin_VisEd' ...
'eegplugin_eepimport' ...
'eegplugin_bdfimport' ...
'eegplugin_brainmovie' ...
'eegplugin_bva_io' ...
'eegplugin_ctfimport' ...
'eegplugin_dipfit' ...
'eegplugin_erpssimport' ...
'eegplugin_fmrib' ...
'eegplugin_iirfilt' ...
'eegplugin_ascinstep' ...
'eegplugin_loreta' ...
'eegplugin_miclust' ...
'eegplugin_4dneuroimaging' };
for indf = 1:length(funcname)
try
vers = feval(funcname{indf}, gcf, trystrs, catchstrs);
%disp(['EEGLAB: adding "' vers '" plugin' ]);
catch
feval(funcname{indf}, gcf, trystrs, catchstrs);
%disp(['EEGLAB: adding plugin function "' funcname{indf} '"' ]);
end;
end;
else
pluginlist = [];
plugincount = 1;
p = mywhich('eeglab.m');
p = p(1:findstr(p,'eeglab.m')-1);
if strcmpi(p, './') || strcmpi(p, '.\'), p = [ pwd filesep ]; end;
% scan deactivated plugin folder
% ------------------------------
dircontent = dir(fullfile(p, 'deactivatedplugins'));
dircontent = { dircontent.name };
for index = 1:length(dircontent)
funcname = '';
pluginVersion = '';
if exist([p 'deactivatedplugins' filesep dircontent{index}]) == 7
if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..')
tmpdir = dir([ p 'deactivatedplugins' filesep dircontent{index} filesep 'eegplugin*.m' ]);
[ pluginName pluginVersion ] = parsepluginname(dircontent{index});
if ~isempty(tmpdir)
funcname = tmpdir(1).name(1:end-2);
end;
end;
else
if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm'
funcname = dircontent{index}(1:end-2); % remove .m
[ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2));
end;
end;
if ~isempty(pluginVersion)
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
pluginlist(plugincount).foldername = dircontent{index};
if ~isempty(funcname)
pluginlist(plugincount).funcname = funcname(10:end);
else pluginlist(plugincount).funcname = '';
end
if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_'
pluginlist(plugincount).funcname(1) = [];
end;
pluginlist(plugincount).status = 'deactivated';
plugincount = plugincount+1;
end;
end;
% scan plugin folder
% ------------------
dircontent = dir(fullfile(p, 'plugins'));
dircontent = { dircontent.name };
for index = 1:length(dircontent)
% find function
% -------------
funcname = '';
pluginVersion = [];
if exist([p 'plugins' filesep dircontent{index}]) == 7
if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..')
newpath = [ 'plugins' filesep dircontent{index} ];
tmpdir = dir([ p 'plugins' filesep dircontent{index} filesep 'eegplugin*.m' ]);
addpathifnotinlist(fullfile(eeglabpath, newpath));
[ pluginName pluginVersion ] = parsepluginname(dircontent{index});
if ~isempty(tmpdir)
%myaddpath(eeglabpath, tmpdir(1).name, newpath);
funcname = tmpdir(1).name(1:end-2);
end;
% special case of subfolder for Fieldtrip
% ---------------------------------------
if ~isempty(findstr(lower(dircontent{index}), 'fieldtrip'))
addpathifnotexist( fullfile(eeglabpath, newpath, 'compat') , 'electrodenormalize' );
addpathifnotexist( fullfile(eeglabpath, newpath, 'forward'), 'ft_sourcedepth.m');
addpathifnotexist( fullfile(eeglabpath, newpath, 'utilities'), 'ft_datatype.m');
ptopoplot = fileparts(mywhich('cbar'));
ptopoplot2 = fileparts(mywhich('topoplot'));
if ~isequal(ptopoplot, ptopoplot2)
addpath(ptopoplot);
end;
end;
% special case of subfolder for BIOSIG
% ------------------------------------
if ~isempty(findstr(lower(dircontent{index}), 'biosig')) && isempty(findstr(lower(dircontent{index}), 'biosigplot'))
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't200_FileAccess'), 'sopen.m');
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't250_ArtifactPreProcessingQualityControl'), 'regress_eog.m' );
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 'doc'), 'DecimalFactors.txt');
end;
end;
else
if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm'
funcname = dircontent{index}(1:end-2); % remove .m
[ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2));
end;
end;
% execute function
% ----------------
if ~isempty(pluginVersion) || ~isempty(funcname)
if isempty(funcname)
%disp([ 'EEGLAB: adding "' pluginName '" to the path; subfolders (if any) might be missing from the path' ]);
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
pluginlist(plugincount).foldername = dircontent{index};
pluginlist(plugincount).status = 'ok';
plugincount = plugincount+1;
else
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
vers = pluginlist(plugincount).version; % version
vers2 = '';
status = 'ok';
pluginlist(plugincount).funcname = funcname(10:end);
pluginlist(plugincount).foldername = dircontent{index};
[tmp pluginlist(plugincount).versionfunc] = parsepluginname(vers2);
if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_'
pluginlist(plugincount).funcname(1) = [];
end;
if strcmpi(status, 'ok')
if isempty(vers), vers = pluginlist(plugincount).versionfunc; end;
if isempty(vers), vers = '?'; end;
%fprintf('EEGLAB: adding "%s" v%s (see >> help %s)\n', ...
%pluginlist(plugincount).plugin, vers, funcname);
end;
pluginlist(plugincount).status = status;
plugincount = plugincount+1;
end;
end;
end;
end; % iseeglabdeployed2
% Path exception for BIOSIG (sending BIOSIG down into the path)
biosigpathlast; % fix str2double issue
if ~ismatlab, return; end;
function rmpathifpresent(newpath);
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpath = [ newpath ';' ];
else
newpath = [ newpath ':' ];
end;
if ismatlab
p = matlabpath;
else p = path;
end;
ind = strfind(p, newpath);
if ~isempty(ind)
rmpath(newpath);
end;
% add path only if it is not already in the list
% ----------------------------------------------
function addpathifnotinlist(newpath);
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpathtest = [ newpath ';' ];
else
newpathtest = [ newpath ':' ];
end;
if ismatlab
p = matlabpath;
else p = path;
end;
ind = strfind(p, newpathtest);
if isempty(ind)
if exist(newpath) == 7
addpath(newpath);
end;
end;
function addpathifnotexist(newpath, functionname);
tmpp = mywhich(functionname);
if isempty(tmpp)
addpath(newpath);
end;
% find a function path and add path if not present
% ------------------------------------------------
function myaddpath(eeglabpath, functionname, pathtoadd);
tmpp = mywhich(functionname);
tmpnewpath = [ eeglabpath pathtoadd ];
if ~isempty(tmpp)
tmpp = tmpp(1:end-length(functionname));
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
%disp([ tmpp ' | ' tmpnewpath '(' num2str(~strcmpi(tmpnewpath, tmpp)) ')' ]);
if ~strcmpi(tmpnewpath, tmpp)
warning('off', 'MATLAB:dispatcher:nameConflict');
addpath(tmpnewpath);
warning('on', 'MATLAB:dispatcher:nameConflict');
end;
else
%disp([ 'Adding new path ' tmpnewpath ]);
addpathifnotinlist(tmpnewpath);
end;
function val = iseeglabdeployed2;
%val = 1; return;
if exist('isdeployed')
val = isdeployed;
else val = 0;
end;
function buildhelpmenu;
% parse plugin function name
% --------------------------
function [name, vers] = parsepluginname(dirName);
ind = find( dirName >= '0' & dirName <= '9' );
if isempty(ind)
name = dirName;
vers = '';
else
ind = length(dirName);
while ind > 0 && ((dirName(ind) >= '0' & dirName(ind) <= '9') || dirName(ind) == '.' || dirName(ind) == '_')
ind = ind - 1;
end;
name = dirName(1:ind);
vers = dirName(ind+1:end);
vers(find(vers == '_')) = '.';
end;
% required here because path not added yet
% to the admin folder
function res = ismatlab;
v = version;
if v(1) > '4'
res = 1;
else
res = 0;
end;
function res = mywhich(varargin);
try
res = which(varargin{:});
catch
fprintf('Warning: permission error accesssing %s\n', varargin{1});
end;
|
github
|
lcnbeapp/beapp-master
|
read_mff_data_block.m
|
.m
|
beapp-master/functions/read_mff_data_block.m
| 787 |
utf_8
|
affe9d914627a34be60349c001976ed4
|
% Original function written by Colin Davey for EGI API
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
function data = read_mff_data_block(binObj, blocks, blockInd)
blockObj = blocks.get(blockInd);
% to access the data for a block, it must be loaded first
blockObj = binObj.loadSignalBlockData(blockObj);
numChannels = blockObj.numberOfSignals;
% number of 4 byte floats is 1/4 the data block size
% That is divided by channel count to get data for each channel:
samplesTimesChannels = blockObj.dataBlockSize/4;
numSamples = samplesTimesChannels / numChannels;
% get first block, returned as bytes.
data = blockObj.data;
% convert bytes to equivalent floating point values
data = typecast(data,'single');
data = reshape(data, numSamples, numChannels)';
end
|
github
|
lcnbeapp/beapp-master
|
mff_getObject.m
|
.m
|
beapp-master/functions/mff_getObject.m
| 1,810 |
utf_8
|
eedf2cef694832c13457e149a12450a5
|
%% mff_getObject.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 12/3/2013
% Copyright 2012, 2013 EGI. All rights reserved.
% Support routine for MFF Matlab code. Not intended to be called directly.
%
% Returns objects of various types:
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Any
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Categories
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Coordinates
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Epochs
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_EventTrack
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_History
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Info
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_InfoN
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_MFFFile
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Photogrammetry
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_PNSSet
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_SensorLayout
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Signal
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Subject
% com.egi.services.mff.api.MFFResourceType.kMFF_RT_Unknown
%%
function theObject = mff_getObject(objType, filename, path)
URI = path;
if objType ~= com.egi.services.mff.api.MFFResourceType.kMFF_RT_MFFFile
URI = [URI filesep filename];
end
delegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
factory = javaObject('com.egi.services.mff.api.MFFFactory', delegate);
resourceVal = objType;
resourceType = javaObject('com.egi.services.mff.api.MFFResourceType', resourceVal);
% fprintf('%s %s\n', char(URI), char(resourceType));
theObject = factory.openResourceAtURI(URI, resourceType);
if ~isempty(theObject)
theObject.loadResource();
end
|
github
|
lcnbeapp/beapp-master
|
extract_separate_file_segment_info.m
|
.m
|
beapp-master/functions/extract_separate_file_segment_info.m
| 2,783 |
utf_8
|
4e3b1211a56b86d3bd1a0f0c9d4eb639
|
%% this functionality is not yet supported and should not be used by most users
% will eventually align segment information from hand edited files that are
% exported as segments with continuous recordings
function extract_separate_file_segment_info(grp_proc_info_in)
%% set path, generate filelist
if (exist(grp_proc_info_in.beapp_format_mff_jar_lib,'file')~=2)
error('EGI MFF JAR Library needed-- specify in proc_info');
end
javaaddpath(which(grp_proc_info_in.beapp_format_mff_jar_lib));
cd(grp_proc_info_in.seg_info_mff_src_dir{1});
mff_flist = dir('*.mff');
seg_info_src_flist = {mff_flist.name};
seg_info_beapp_flist = strrep(seg_info_src_flist, '.mff', '.mat');
seg_info_out_dir = [grp_proc_info_in.beapp_toggle_mods{'format','Module_Dir'}{1} filesep 'seg_info'];
if ~isdir(seg_info_out_dir)
mkdir(seg_info_out_dir);
end
% extract events and eeg data for each file
for curr_file=1:length(seg_info_src_flist)
curr_fname = seg_info_src_flist{curr_file};
full_filepath=strcat(grp_proc_info_in.seg_info_mff_src_dir{1},filesep,curr_fname);
cd(full_filepath)
% get list of files containing signal using EGI API function
curr_file_obj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_MFFFile, [], full_filepath);
bin_flist = curr_file_obj.getSignalResourceList(false);
% will need modification if more than one .bin file - not seen to date
if length(bin_flist)>1
error('Developer:more than one signal file, adjust script')
% will also affect infoN file/ infoN_obj
else
%% read mff demographic data
signal_string=char(bin_flist(1));
signal_string=char(signal_string(2:end-1)); % in case need to change to loop
% load demographic info, net, and eeg blocks
signal_obj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Signal, signal_string, full_filepath);
sig_blocks = signal_obj.getSignalBlocks();
block_obj = sig_blocks.get(0);
info_obj=mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Info, 'info.xml', full_filepath);
mff_version=info_obj.getMFFVersion;
if mff_version==0
time_units_exp= 9;
else
time_units_exp=6;
end
record_time = info_obj.getRecordTime;
file_proc_info.beapp_srate = double(block_obj.signalFrequency(1));
file_proc_info=read_mff_segment_info(full_filepath,file_proc_info,time_units_exp,record_time);
%clear time_units_exp
end
segment_info = file_proc_info.seg_info;
tasks = file_proc_info.seg_tasks;
cd(seg_info_out_dir)
split_fname = strsplit(curr_fname,'.');
save([split_fname{1} '.mat'],'segment_info','tasks');
end
chk = 0;
|
github
|
lcnbeapp/beapp-master
|
beapp_calc_comod.m
|
.m
|
beapp-master/functions/beapp_calc_comod.m
| 6,503 |
utf_8
|
82bb8be11000ade48121e4d45affa9eb
|
%% beapp_calc_comod: takes a signal (eeg data section) and generates a PAC comodulogram
function [comodulogram, result_z_scores, result_surr_max, phase_bins, amp_dist, phase_dist] = beapp_calc_comod(signal,srate,low_fq_range,high_fq_range,...
method,low_fq_width,high_fq_width,low_fq_res,high_fq_res,calc_zscores,pac_variable_hf_filt)
signal = py.numpy.array(signal);
%set settings for pactools
curr_results = NaN(size(high_fq_range,2),size(low_fq_range,2));
result_z_scores = NaN(size(high_fq_range,2),size(low_fq_range,2));
if calc_zscores
amp_dist = NaN(size(high_fq_range,2),size(low_fq_range,2),18,201);
else
amp_dist = NaN(size(high_fq_range,2),size(low_fq_range,2),18);
end
for lf = 1:size(low_fq_range,2)
for hf = 1:size(high_fq_range,2)
estimator = py.pactools.Comodulogram(srate,low_fq_range(lf));
estimator.progress_bar = 0; %set to 0 cause it's broken
estimator.method = py.str(method);
estimator.high_fq_range = high_fq_range(hf);
estimator.low_fq_width = py.float(low_fq_width);
if pac_variable_hf_filt
hf_low = high_fq_range(hf) - 2;
hf_high = high_fq_range(hf)+low_fq_range(lf);
estimator.high_fq_width = hf_high - hf_low;
estimator.high_fq_range = hf_low + (hf_high - hf_low)/2;
else
estimator.high_fq_width = py.float(high_fq_width);
end
if calc_zscores
% if ~compute_shifts
% %estimator.shifts_ = shifts;
% end
estimator.compute_shifts = 1;
estimator.n_surrogates = py.int(200);
estimator.minimum_shift = 0.1;
end
fit = estimator.fit(signal);
phase_bins = double(py.array.array('d',py.numpy.nditer(fit.phase_bins)));
phase_dist = phase_bins;
%comodulogram = reshape(curr_results,[high_fq_res low_fq_res]);
if calc_zscores %curr results not set if calc_zscores??
allamps = double(py.array.array('d',py.numpy.nditer(fit.amp_dist)));
amp_dist(hf,lf,:,:) = reshape(allamps,[18 201]); %shouldn't be hardcoded
divergence_kl = sum(amp_dist(hf,lf,:,1) .* log(amp_dist(hf,lf,:,1) * 18));
curr_results(hf,lf) = divergence_kl / log(18);
%result_z_scores(hf,lf) = double(py.array.array('d',py.numpy.nditer(fit.comod_z_score_)));
%result_z_scores = reshape(result_z_scores,[high_fq_res low_fq_res]);
else
amp_dist(hf,lf,:) = double(py.array.array('d',py.numpy.nditer(fit.amp_dist)));
divergence_kl = sum(amp_dist(hf,lf,:) .* log(amp_dist(hf,lf,:) * 18));
curr_results(hf,lf) = divergence_kl / log(18);
end
for surr = 1:size(amp_dist,4)
amp_dist(hf,lf,:,surr) = amp_dist(hf,lf,:,surr) ./ sum(amp_dist(hf,lf,:,surr));
result_surr_max = NaN(1,200);
end
end
end
comodulogram = curr_results;
% elseif michaelsaysso == 0
% estimator = py.pactools.Comodulogram(srate,low_fq_range);
% estimator.high_fq_range = high_fq_range;
% estimator.progress_bar = 0; %set to 0 cause it's broken
% estimator.method = py.str(method);
% %estimator.n_jobs = py.int(2); %temp for super comp
% estimator.low_fq_width = py.float(low_fq_width);
% if calc_zscores
% estimator.n_surrogates = py.int(200);
% end
% %estimator.ax_special = py.matplotlib.pyplot.plot(); %TEMP
% estimator.high_fq_width = py.float(high_fq_width); %TEMP:
% %let pactools set
% fit = estimator.fit(signal);
% curr_results = double(py.array.array('d',py.numpy.nditer(fit.comod_)));
% phase_bins = double(py.array.array('d',py.numpy.nditer(fit.phase_bins)));
% %phase_bins = NaN;
% %amp_dist = NaN(1,18);
% amp_dist = double(py.array.array('d',py.numpy.nditer(fit.amp_dist)));
% comodulogram = reshape(curr_results,[high_fq_res low_fq_res]);
% if calc_zscores
% result_z_scores = double(py.array.array('d',py.numpy.nditer(fit.comod_z_score_)));
% result_z_scores = reshape(result_z_scores,[high_fq_res low_fq_res]);
% result_surr_max = double(py.array.array('d',py.numpy.nditer(fit.surrogate_max_)));
% %result_surr_max = reshape(result_surr_max,[high_fq_res low_fq_res]);
% else
% result_z_scores = NaN(size(comodulogram,1),size(comodulogram,2));
% result_surr_max = NaN(1,200);
% end
% %collect phase dist, amp dist of channels
% elseif michaelsaysso == 2
%
% estimator = py.pactools.Comodulogram(srate,low_fq_range);
% estimator.high_fq_range = high_fq_range;
% estimator.progress_bar = 0; %set to 0 cause it's broken
% estimator.method = py.str(method);
% %estimator.n_jobs = py.int(2); %temp for super comp
% estimator.low_fq_width = py.float(low_fq_width);
% if calc_zscores
% estimator.n_surrogates = py.int(200);
% end
% %estimator.ax_special = py.matplotlib.pyplot.plot(); %TEMP
% estimator.high_fq_width = py.float(high_fq_width); %TEMP:
% %let pactools set
% fit = estimator.fit(signal);
% %curr_results = double(py.array.array('d',py.numpy.nditer(fit.comod_)));
% phase_bins = double(py.array.array('d',py.numpy.nditer(fit.phase_bins)));
% %phase_bins = NaN;
% %amp_dist = NaN(1,18);
% amp_dist = double(py.array.array('d',py.numpy.nditer(fit.amp_dist)));
% amps = double(py.array.array('d',py.numpy.nditer(fit.amp)));
% % = reshape(curr_results,[high_fq_res low_fq_res]);
% phase_dist = double(py.array.array('d',py.numpy.nditer(fit.phase)));
% %procedure from pactools:
% %digitize phase dist
% %then for b in np.unique(phase_preprocessed):
% % selection = amplitude[phase_preprocessed == b]
% % amplitude_dist[b] = np.mean(selection)
% %my attempt to do things myself...doesn't replicate
% %%THE AMPLITUDE DIST HERE IS ALL LF AMPLITUDE DISTS APPENDED
% %%TOGETHER...NEED TO CALC ONE AT A TIME
% phase_binned = discretize(phase_dist,18);
% for b=1:18
% selection = amp_dist(phase_binned==b);
% amplitude_dist(b) = mean(selection);
% end
%
% end
% curr_amp = double(py.array.array('d',py.numpy.nditer(fit.amp)));
% curr_phase = double(py.array.array('d',py.numpy.nditer(fit.phase)));
% rounded_phase = round(curr_phase,2);
% rounded_amp = NaN(1000,size(phase_range,2));
% curr_chan_phase_amp(seg,:) = nanmean(rounded_amp,1);
|
github
|
lcnbeapp/beapp-master
|
beapp_calc_mi_zscore.m
|
.m
|
beapp-master/functions/beapp_calc_mi_zscore.m
| 2,581 |
utf_8
|
21ee00e3be5775927b1760ec37df1e4c
|
%Calculates a comodulogram of MIs, phase_biases. If user selects to calculate z-scores,
%z-scored MIs are also calculated/
%Instead of calculating the MI of each segment separately, and then
%averaging those values, this function averaged the amplitude distributions
%across the segments, and then calculated the MI on these averaged
%amplitude distributions. Otherwise, MI increases more with noise, since
%each segment contains few samples.
function [new_zscore_comod, rawmi_comod, phase_bias_comod] = beapp_calc_mi_zscore(amp_dist,calc_zscore)
n_bins = 18;
new_zscore_comod = NaN(size(amp_dist,1),size(amp_dist,2),size(amp_dist,4));
rawmi_comod = NaN(size(amp_dist,1),size(amp_dist,2),size(amp_dist,4));
phase_bias_comod = NaN(size(amp_dist,1),size(amp_dist,2),size(amp_dist,4));
for chan = 1:size(amp_dist,4)
if ~isnan(amp_dist(1,1,1,chan,1))
for hf = 1:size(amp_dist,1)
for lf = 1:size(amp_dist,2)
%calc MI on hf, lf, chan, surrogate
if calc_zscore
surr_mis = NaN(1,size(amp_dist,5)-1);
end
for surr = 1:size(amp_dist,5)
amp_dist(hf,lf,:,chan,surr) = amp_dist(hf,lf,:,chan,surr) ./ sum(amp_dist(hf,lf,:,chan,surr));
amplitude_dist = amp_dist(hf,lf,:,chan,surr);
amplitude_dist = squeeze(amplitude_dist)';
divergence_kl = sum(amplitude_dist .* log(amplitude_dist * n_bins));
if surr == 1
real_mi = divergence_kl / log(n_bins);
rawmi_comod(hf,lf,chan) = real_mi;
else
surr_mis(1,surr-1) = divergence_kl / log(n_bins);
end
end
for surr = 1:size(amp_dist,5)
amplitude_dist = amp_dist(hf,lf,10:18,chan,surr);
amplitude_dist = squeeze(amplitude_dist)';
sum_dist = 0;
for bin = 1:9
sum_dist = sum_dist+amplitude_dist(1,bin);
end
phase_bias_comod(hf,lf,chan,surr) = sum_dist;
end
if calc_zscore
comod_z_score = real_mi;
comod_z_score = comod_z_score - mean(surr_mis,2);
comod_z_score = comod_z_score / std(surr_mis);
new_zscore_comod(hf,lf,chan) = comod_z_score;
end
end
end
end
end
|
github
|
lcnbeapp/beapp-master
|
fooof.m
|
.m
|
beapp-master/functions/fooof.m
| 3,761 |
utf_8
|
c7bd4b92ea4c9151d15a69ad556be47b
|
% fooof() - run the fooof model on a neural power spectrum
%
% Usage:
% >> fooof_results = fooof(freqs, psd, f_range, settings);
%
% Inputs:
% freqs = row vector of frequency values
% psd = row vector of power values
% f_range = fitting range (Hz)
% settings = fooof model settings, in a struct, including:
% settings.peak_width_limts
% settings.max_n_peaks
% settings.min_peak_amplitude
% settings.peak_threshold
% settings.background_mode
% settings.verbose
%
% Outputs:
% fooof_results = fooof model ouputs, in a struct, including:
% fooof_results.background_params
% fooof_results.peak_params
% fooof_results.gaussian_params
% fooof_results.error
% fooof_results.r_squared
%
% Notes
% Not all settings need to be set. Any settings that are not
% provided as set to default values. To run with all defaults,
% input settings as an empty struct.
function fooof_results = fooof(freqs, psd, f_range, settings, filename, grp_proc_info_in, save_report)
% Check settings - get defaults for those not provided
settings = fooof_check_settings(settings);
% Convert inputs
freqs_py = py.numpy.array(freqs);
psd_py = py.numpy.array(psd);
f_range = py.list(f_range);
width_range = py.list(settings.peak_width_limits);
% Initialize FOOOF object
fm = py.fooof.FOOOF(width_range, ...
settings.max_n_peaks, ...
settings.min_peak_amplitude, ...
settings.peak_threshold, ...
settings.background_mode, ...
settings.verbose);
% Run FOOOF fit
fm.fit(freqs_py, psd_py, f_range)
% Extract outputs
fooof_results = fm.get_results();
fooof_results = fooof_unpack_results(fooof_results);
%CD into fooof directory, save report
if save_report == 1 %temp: allow it for everything unconditionally
cd(grp_proc_info_in.beapp_toggle_mods{'fooof','Module_Dir'}{1});
% fm.save_report(filename); -- stopped working
% fm.report(freqs,psd,f_range)
if grp_proc_info_in.fooof_background_mode == 1 %fixed
fooofed_psd = fooof_results.background_params(1,1) - log10(freqs.^fooof_results.background_params(1,2)); %knee parameter is 0, and not output
else %knee
fooofed_psd = fooof_results.background_params(1,1) - log10(fooof_results.background_params(1,2) + freqs.^fooof_results.background_params(1,3));
%fooofed_psd = 10^fooof_results.background_params(1,1) * (1./(fooof_results.background_params(1,2)+freqs.^fooof_results.background_params(1,3)));
end
background_fit = fooofed_psd;
for i=1:size(fooof_results.peak_params,1)
fooofed_psd = fooofed_psd + fooof_results.gaussian_params(i,2) * exp(-((freqs - fooof_results.gaussian_params(i,1)).^2) / (2*fooof_results.gaussian_params(i,3)).^2);
end
h = figure;
plot(freqs,log10(psd),freqs,fooofed_psd,freqs,background_fit,'--')
xlabel('Frequency')
ylabel('Power')
legend('Original Spectrum', 'Full Model Fit', 'Background Fit')
saveas(h, strcat(filename,'.png'))
src_dir = find_input_dir('fooof',grp_proc_info_in.beapp_toggle_mods);
close;
cd(src_dir{1});
end
% %%--FOR TESTING--%%
% x = rand;
% if x < .1
% cd(grp_proc_info_in.beapp_toggle_mods{'fooof','Module_Dir'}{1});
% fm.save_report(filename);
% src_dir = find_input_dir('fooof',grp_proc_info_in.beapp_toggle_mods);
% cd(src_dir{1});
% end
clearvars -except fooof_results grp_proc_info_in
end
|
github
|
lcnbeapp/beapp-master
|
beapp_create_REST_lead_matrix.m
|
.m
|
beapp-master/functions/beapp_create_REST_lead_matrix.m
| 1,833 |
utf_8
|
a55a2a87491440a4c5d4f46b3f0e38a4
|
% version of the REST_Reference_Callback function taken from the REST
% toolbox to correspond with BEAPP format.
% calls REST toolbox Lead_Field software to create lead field matrix
% The REST Toolbox:
% Li Dong*, Fali Li, Qiang Liu, Xin Wen, Yongxiu Lai, Peng Xu and Dezhong Yao*.
% MATLAB Toolboxes for Reference Electrode Standardization Technique (REST) of Scalp EEG.
% Frontiers in Neuroscience, 2017:11(601).
function beapp_create_REST_lead_matrix(net_library_location, sensor_layout, sensor_layout_short_name,sensor_layout_long_name)
make_lead_matrix_prompt = questdlg(sprintf(['Would you like to create a REST Lead Matrix for this layout (' sensor_layout_long_name ')? \n',...
'Note: only an option for Windows']), 'Create REST Lead Matrix', 'No', 'Yes', 'Yes');
if strcmp( make_lead_matrix_prompt,'Yes')
if ~ispc
warndlg('REST Lead Matrices can only be created on a PC');
return;
else
% create ascii file
cd([net_library_location, filesep, 'REST_lead_field_library']);
cart_double = horzcat([sensor_layout(:).X]',[sensor_layout(:).Y]',[sensor_layout(:).Z]');
save([sensor_layout_short_name '_REST_ascii_coords.txt'], 'cart_double','-ascii');
waitfor(msgbox(sprintf(['The REST Lead Field calculation program will now open.\n',...
'From the LeadField GUI, load the .txt file in the REST matrix library folder ',...
'with the same layout variable name as the current net, and then calculate matrix'])));
% create lead matrix
uiopen('LeadField.exe',1)
waitfor(msgbox('Click OK when LeadField matrix calculation is completely done for this sensor layout'));
movefile('Lead_Field.dat',[sensor_layout_short_name '_REST_lead_field.dat']);
end
else
return;
end
|
github
|
lcnbeapp/beapp-master
|
load_REST_lead_matrices_and_create_gs.m
|
.m
|
beapp-master/functions/load_REST_lead_matrices_and_create_gs.m
| 1,398 |
utf_8
|
bf742071c1369a6a55b5e341d574d4d8
|
% version of a function taken from the REST toolbox to correspond with BEAPP format:
% The REST Toolbox:
% Li Dong*, Fali Li, Qiang Liu, Xin Wen, Yongxiu Lai, Peng Xu and Dezhong Yao*.
% MATLAB Toolboxes for Reference Electrode Standardization Technique (REST) of Scalp EEG.
% Frontiers in Neuroscience, 2017:11(601).
function [leads] = load_REST_lead_matrices_and_create_gs(grp_proc_info_in)
load(grp_proc_info_in.ref_net_library_options);
for curr_net = 1:length(grp_proc_info_in.src_unique_nets)
get_net_row_ind = find(ismember(net_library_options.Net_Full_Name,grp_proc_info_in.src_unique_nets(curr_net)));
sensor_layout_short_name = net_library_options.Net_Variable_Name{get_net_row_ind};
if ~exist([grp_proc_info_in.ref_net_library_dir,...
filesep, 'REST_lead_field_library' filesep sensor_layout_short_name '_REST_lead_field.dat'],'file')
disp(['Creating lead matrix for layout:' net_library_options.Net_Full_Name{get_net_row_ind}]);
beapp_create_REST_lead_matrix(grp_proc_info_in.ref_net_library_dir,...
grp_proc_info_in.src_unique_net_vstructs{curr_net}, sensor_layout_short_name,grp_proc_info_in.src_unique_nets{curr_net});
end
leads{curr_net}= load([grp_proc_info_in.ref_net_library_dir,...
filesep, 'REST_lead_field_library' filesep sensor_layout_short_name '_REST_lead_field.dat']);
end
|
github
|
lcnbeapp/beapp-master
|
fooof_check_settings.m
|
.m
|
beapp-master/functions/fooof_check_settings.m
| 735 |
utf_8
|
1288684349fda0893e8d12f386f68e6c
|
% Check fooof settings, provided as a struct
% Any settings not specified are set to default values
function settings = fooof_check_settings(settings)
if ~isfield(settings, 'peak_width_limits')
settings.peak_width_limits = [0.5, 12];
end
if ~isfield(settings, 'max_n_peaks')
settings.max_n_peaks = Inf;
end
if ~isfield(settings, 'min_peak_amplitude')
settings.min_peak_amplitude = 0.0;
end
if ~isfield(settings, 'peak_threshold')
settings.peak_threshold = 2.0;
end
if ~isfield(settings, 'background_mode')
settings.background_mode = 'fixed';
end
if ~isfield(settings, 'verbose')
settings.verbose = true;
end
end
|
github
|
lcnbeapp/beapp-master
|
detrend_biosig_nan.m
|
.m
|
beapp-master/functions/detrend_biosig_nan.m
| 4,727 |
utf_8
|
b66e0b644dc203fc9f62131271b359c2
|
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
function [X,T]=detrend_biosig_nan(t,X,p)
% DETREND removes the trend from data, NaN's are considered as missing values
%
% DETREND is fully compatible to previous Matlab and Octave DETREND with the following features added:
% - handles NaN's by assuming that these are missing values
% - handles unequally spaced data
% - second output parameter gives the trend of the data
% - compatible to Matlab and Octave
%
% [...]=detrend([t,] X [,p])
% removes trend for unequally spaced data
% t represents the time points
% X(i) is the value at time t(i)
% p must be a scalar
%
% [...]=detrend(X,0)
% [...]=detrend(X,'constant')
% removes the mean
%
% [...]=detrend(X,p)
% removes polynomial of order p (default p=1)
%
% [...]=detrend(X,1) - default
% [...]=detrend(X,'linear')
% removes linear trend
%
% [X,T]=detrend(...)
%
% X is the detrended data
% T is the removed trend
%
% see also: SUMSKIPNAN, ZSCORE
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; If not, see <http://www.gnu.org/licenses/>.
% Copyright (C) 1995, 1996 Kurt Hornik <[email protected]>
% $Id: detrend.m 8223 2011-04-20 09:16:06Z schloegl $
% Copyright (C) 2001,2007 by Alois Schloegl <[email protected]>
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
if (nargin == 1)
p = 1;
X = t;
t = [];
elseif (nargin == 2)
if strcmpi(X,'constant'),
p = 0;
X = t;
t = [];
elseif strcmpi(X,'linear'),
p = 1;
X = t;
t = [];
elseif ischar(X)
error('unknown 2nd input argument');
elseif all(size(X)==1),
p = X;
X = t;
t = [];
else
p = 1;
end;
elseif (nargin == 3)
if ischar(X),
warning('input arguments are not supported');
end;
elseif (nargin > 3)
fprintf (1,'usage: detrend (x [, p])\n');
end;
% check data, must be in culomn order
[m, n] = size (X);
if (m == 1)
X = X';
r=n;
else
r=m;
end
% check time scale
if isempty(t),
t = (1:r).'; % make time scale
elseif ~all(size(t)==size(X))
t = t(:);
end;
% check dimension of t and X
if ~all(size(X,1)==size(t,1))
fprintf (2,'detrend: size(t,1) must same as size(x,1) \n');
end;
% check the order of the polynomial
if (~(all(size(p)==1) && (p == round (p)) && (p >= 0)))
fprintf (2,'detrend: p must be a nonnegative integer\n');
end
if (nargout>1) , % needs more memory
T = zeros(size(X))+nan;
%T=repmat(nan,size(X)); % not supported by Octave 2.0.16
if (size(t,2)>1), % for multiple time scales
for k=1:size(X,2),
idx=find(~isnan(X(:,k)));
b = (t(idx,k) * ones (1, p + 1)) .^ (ones (length(idx),1) * (0 : p));
T(idx,k) = b * (b \ X(idx,k));
end;
else % if only one time scale is used
b = (t * ones (1, p + 1)) .^ (ones (length(t),1) * (0 : p));
for k=1:size(X,2),
idx=find(~isnan(X(:,k)));
T(idx,k) = b(idx,:) * (b(idx,:) \ X(idx,k));
%X(idx,k) = X(idx,k) - T(idx,k); % 1st alternative implementation
%X(:,k) = X(:,k) - T(:,k); % 2nd alternative
end;
end;
X = X-T; % 3nd alternative
if (m == 1)
X = X';
T = T';
end
else % needs less memory
if (size(t,2)>1), % for multiple time scales
for k = 1:size(X,2),
idx = find(~isnan(X(:,k)));
b = (t(idx,k) * ones (1, p + 1)) .^ (ones (length(idx),1) * (0 : p));
X(idx,k) = X(idx,k) - b * (b \ X(idx,k));
end;
else % if only one time scale is used
b = (t * ones (1, p + 1)) .^ (ones (length(t),1) * (0 : p));
for k = 1:size(X,2),
idx = find(~isnan(X(:,k)));
X(idx,k) = X(idx,k) - b(idx,:) * (b(idx,:) \ X(idx,k));
end;
end;
if (m == 1)
X = X';
end
end;
|
github
|
lcnbeapp/beapp-master
|
batch_eeglab2beapp.m
|
.m
|
beapp-master/functions/batch_eeglab2beapp.m
| 8,091 |
utf_8
|
c2e837872cf68051dd87d5acd0a3094e
|
function grp_proc_info_in = batch_eeglab2beapp (grp_proc_info_in)
% get file list and extract file specific information from input tables
[grp_proc_info_in.src_fname_all,grp_proc_info_in.src_linenoise_all,...
grp_proc_info_in.src_offsets_in_ms_all,grp_proc_info_in.beapp_fname_all,grp_proc_info_in.src_net_typ_all] = ...
beapp_load_nonmat_flist_and_evt_table(grp_proc_info_in.src_dir,'.set',...
grp_proc_info_in.event_tag_offsets,grp_proc_info_in.src_linenoise,grp_proc_info_in.beapp_file_info_table,...
grp_proc_info_in.src_format_typ,grp_proc_info_in.beapp_run_per_file,grp_proc_info_in.beapp_file_idx);
if isempty(grp_proc_info_in.src_net_typ_all)
error('Please include sensor layout information in beapp_file_info_table');
end
grp_proc_info_in.src_unique_nets = unique(grp_proc_info_in.src_net_typ_all);
% if user wants to ignore specific channels, store which channels for which
% nets (otherwise get all net information from beapp_file_info_table)
if ~isempty(grp_proc_info_in.beapp_indx_chans_to_exclude)
if ~(isequal(length(grp_proc_info_in.src_unique_nets),length(grp_proc_info_in.beapp_indx_chans_to_exclude))&& ~isempty(grp_proc_info_in.src_unique_nets))
if isempty(grp_proc_info_in.src_unique_nets)
error ('User has asked to exclude channels but not included net information in grp_proc_info.src_unique_nets');
elseif ~isequal(length(grp_proc_info_in.src_unique_nets),length(grp_proc_info_in.beapp_indx_chans_to_exclude))
error ('User has asked to exclude channels but number of nets in grp_proc_info.src_unique_nets does not \n%s',...
'correspond to number of nets expected from grp_proc_info.beapp_indx_chans_to_exclude');
end
end
end
% load nets the user has input, for speed
if ~isempty(grp_proc_info_in.src_unique_nets{1})
% add new nets if not in library, load nets used into grp_proc_info_in
add_nets_to_library(grp_proc_info_in.src_unique_nets,grp_proc_info_in.ref_net_library_options,grp_proc_info_in.ref_net_library_dir,grp_proc_info_in.ref_eeglab_loc_dir,grp_proc_info_in.name_10_20_elecs);
[grp_proc_info_in.src_unique_net_vstructs,grp_proc_info_in.src_unique_net_ref_rows, grp_proc_info_in.src_net_10_20_elecs,grp_proc_info_in.largest_nchan] = load_nets_in_dataset(grp_proc_info_in.src_unique_nets,grp_proc_info_in.ref_net_library_options, grp_proc_info_in.ref_net_library_dir);
cd(grp_proc_info_in.src_dir{1});
end
%% convert each file to BEAPP structure
for curr_file = 1: length(grp_proc_info_in.src_fname_all)
tic;
% save filename and path
file_proc_info.src_fname=grp_proc_info_in.src_fname_all(curr_file);
file_proc_info.beapp_fname=grp_proc_info_in.beapp_fname_all(curr_file);
full_filepath=strcat(grp_proc_info_in.src_dir{1},filesep,file_proc_info.src_fname{1});
EEG_struct = pop_loadset(full_filepath);
%% read eeglab file metadata
[grp_proc_info_in,file_proc_info] = beapp_read_eeglab_metadata (grp_proc_info_in,file_proc_info, EEG_struct,curr_file);
%% initialize file channel related variables
beapp_indx_init = 1:file_proc_info.src_nchan;
if ~isempty(grp_proc_info_in.beapp_indx_chans_to_exclude)
uniq_net_ind = find(strcmp(grp_proc_info_in.src_unique_nets, file_proc_info.net_typ{1}));
chans_to_exclude = grp_proc_info_in.beapp_indx_chans_to_exclude{uniq_net_ind};
beapp_indx_init = setdiff(beapp_indx_init,chans_to_exclude,'stable');
end
file_proc_info.beapp_indx= cell(file_proc_info.src_num_epochs,1);
file_proc_info.beapp_indx(:) = {[beapp_indx_init]};
file_proc_info.beapp_bad_chans= cell(file_proc_info.src_num_epochs,1);
file_proc_info.beapp_bad_chans(:) = {[]};
file_proc_info.beapp_nchans_used=length(beapp_indx_init)*ones(1,file_proc_info.src_num_epochs);
file_proc_info.beapp_filt_max_freq = NaN;
clear beapp_indx_init
%% read in eeglab events
% event sub function
% add event label, time latency, and sample number to EEGLAB structure
if ~ isempty(EEG_struct.event)
[file_proc_info.evt_info{1}] = beapp_read_eeglab_events(EEG_struct.event,grp_proc_info_in.behavioral_coding.bad_value,...
grp_proc_info_in.src_eeglab_cond_info_field,grp_proc_info_in.src_eeglab_latency_units,file_proc_info,grp_proc_info_in.src_format_typ);
end
% if grp_proc_info_in.src_eeglab_cond_info_loc ==1 % condition information already embedded in .type tags
%
% for curr_tag = 1:length(EEGLAB TAGS_SET_BY_USER)
%
% get_curr_tag_in
%
%
% else % condition info should already be read in
%
%
% end
% % if file has been pre-segmented (should this be assumed if 3-D data in
% % eeglab?)
% if grp_proc_info_in.src_format_typ ==3
% seg_cond_names =
% unique({file_proc_info.seg_info.condition_name});
% file_proc_info.evt_conditions_being_analyzed= table();
% file_proc_info.evt_conditions_being_analyzed.Condition_Name
% (1:length(seg_cond_names),1)= seg_cond_names';
% file_proc_info.evt_conditions_being_analyzed((length(seg_cond_names)+1):end,:)
% =[];
% end
clear curr_file_obj record_time
%% load actual eeg data
eeg = {EEG_struct.data};
% wipe out (NaN) channels appropriately
if ~isempty(grp_proc_info_in.beapp_indx_chans_to_exclude)
eeg = cellfun(@(x) exclude_data_for_chans(chans_to_exclude,x),eeg,'UniformOutput',0);
end
%% format and save
% % delete data inside recording periods not selected
% if ~ isempty(file_proc_info.epoch_inds_to_process)
% try
% eeg = eeg(file_proc_info.epoch_inds_to_process);
% file_proc_info.evt_info = file_proc_info.evt_info(file_proc_info.epoch_inds_to_process);
% file_proc_info.beapp_num_epochs = length(file_proc_info.epoch_inds_to_process);
% file_proc_info.beapp_indx = file_proc_info.beapp_indx(file_proc_info.epoch_inds_to_process);
% file_proc_info.beapp_bad_chans = file_proc_info.beapp_bad_chans(file_proc_info.epoch_inds_to_process);
% file_proc_info.beapp_nchans_used = file_proc_info.beapp_nchans_used(file_proc_info.epoch_inds_to_process);
% catch ME
% if strcmp(ME.identifier,'MATLAB:badsubscript')
% warning ([file_proc_info.beapp_fname{1} ' : does not contain one or all of recording selected in user inputs. Skipping this file in this analysis']);
% continue;
% end
% end
% end
file_proc_info = beapp_prepare_to_save_file('format',file_proc_info, grp_proc_info_in,grp_proc_info_in.src_dir{1});
% if segmented files, make data into condition x epoch array containing
% 3d data arrays, as produces in segmentation modules
% throw out bad segments if desired
if grp_proc_info_in.src_format_typ ==3
if ndims (eeg) <3 && ~isempty(eeg)
% if only one segment, let the user know in case it's
% unsegmented data
warning ([file_proc_info.beapp_fname{1} ': src format typ indicated as segmented .set. File only contains one segment, confirm pre-segmented']);
end
[eeg_w, file_proc_info] = format_segmented_mff_data (eeg,file_proc_info,...
grp_proc_info_in.beapp_event_eprime_values.condition_names,grp_proc_info_in.mff_seg_throw_out_bad_segments);
if ~all(cellfun(@isempty,eeg_w))
save(file_proc_info.beapp_fname{1},'file_proc_info','eeg_w');
end
elseif ~all(cellfun(@isempty,eeg))
save(file_proc_info.beapp_fname{1},'file_proc_info','eeg');
end
clearvars -except grp_proc_info_in curr_file grp_proc_info_in.src_offsets_in_ms_all ref_dir
end
clear grp_proc_info_in.src_srate_all file_proc_info
end
function eeg_curr_rec_period = exclude_data_for_chans(chans_to_exclude,eeg_curr_rec_period)
eeg_curr_rec_period(chans_to_exclude ,:) = deal(NaN);
end
|
github
|
lcnbeapp/beapp-master
|
compute_REST_reref.m
|
.m
|
beapp-master/functions/compute_REST_reref.m
| 1,683 |
utf_8
|
51c86de41591ec327439963cec28eca9
|
% version of the REST_Reference_Callback function taken from the REST toolbox to correspond with BEAPP format:
% The REST Toolbox:
% Li Dong*, Fali Li, Qiang Liu, Xin Wen, Yongxiu Lai, Peng Xu and Dezhong Yao*.
% MATLAB Toolboxes for Reference Electrode Standardization Technique (REST) of Scalp EEG.
% Frontiers in Neuroscience, 2017:11(601).
function rest_ref_eeg_out = compute_REST_reref(eeg_arr_in,lead_field_matrix)
% BEAPP: don't actually need to calculate G every time, but we do here since
% our nets/ lead matrices can change from file to file
if ~isempty(lead_field_matrix)
if (size(lead_field_matrix, 2) == size(eeg_arr_in,1))
G = lead_field_matrix;
G = G';
G_ave = mean(G);
G_ave = G-repmat(G_ave,size(G,1),1);
Ra = G*pinv(G_ave,0.05); %the value 0.05 is for real data; for simulated data, it may be set as zero.
try
Ref_data = [];
tmp_data = eeg_arr_in;
cur_ave = mean(tmp_data);
cur_var1 = tmp_data - repmat(cur_ave,size(tmp_data,1),1);
tmp_data = Ra * cur_var1;
tmp_data = cur_var1 + repmat(mean(tmp_data),size(tmp_data,1),1); % edit by Li Dong (2017.8.28)
% Vr = V_avg + AVG(V_0)
rest_ref_eeg_out = tmp_data;
end
else
errordlg('Wrong Leadfield has been imported, please import the right Leadfield !!!','Error');
return;
end
else
errordlg('No Leadfield has been imported, please import Leadfield !!!','Error');
return;
end
end
|
github
|
lcnbeapp/beapp-master
|
fooof_unpack_results.m
|
.m
|
beapp-master/functions/fooof_unpack_results.m
| 941 |
utf_8
|
3bc34ef5c084798af19241baef790402
|
% Unpack fooof_results python object into matlab struct
function results_out = fooof_unpack_results(results_in)
results_out = struct();
results_out.background_params = ...
double(py.array.array('d', results_in.background_params));
temp = double(py.array.array('d', results_in.peak_params.ravel));
results_out.peak_params = ...
transpose(reshape(temp, 3, length(temp) / 3));
temp = double(py.array.array('d', results_in.gaussian_params.ravel));
results_out.gaussian_params = ...
transpose(reshape(temp, 3, length(temp) / 3));
results_out.error = ...
double(py.array.array('d', py.numpy.nditer(results_in.error)));
% Note: for reasons unknown, r_squared seems to come out as float...
results_out.r_squared = results_in.r_squared;
%results_out.r_squared = ...
% double(py.array.array('d', py.numpy.nditer(results_in.r_squared)));
end
|
github
|
lcnbeapp/beapp-master
|
beapp_gui_edit_seg_settings.m
|
.m
|
beapp-master/functions/gui_functions/beapp_gui_edit_seg_settings.m
| 2,399 |
utf_8
|
6a035e435c091bc1232971ae66b4dc5c
|
function grp_proc_info = beapp_gui_edit_seg_settings (grp_proc_info)
% globals -- will find a way to pass them automatically later
scrsz = get(groot,'ScreenSize');
win_width = scrsz(3)/4;
seg_sub_panel_ctr = 1;
show_back_button = 'off';
strhalt_seg_out = '';
skipline_panel = 'on';
% initialize available panels based on user data type selection (baseline,
% evt, conditioned baseline)
[seg_sub_panel_list, show_next_button] = adjust_seg_panel_list (grp_proc_info.src_data_type);
while ~strcmp(strhalt_seg_out,'returninginputui_done')
current_sub_panel = seg_sub_panel_list{seg_sub_panel_ctr};
[seg_button_list,seg_button_geometry,seg_ver_geometry,skipline_panel] = beapp_gui_seg_subfunction_prep (current_sub_panel,grp_proc_info);
[~, ~, strhalt_seg, resstruct_seg_settings, ~] = inputgui_mod_for_beapp('geometry',seg_button_geometry ,...
'uilist',seg_button_list,'minwidth',win_width,'nextbutton',show_next_button,'backbutton',show_back_button,...
'title','BEAPP Segmentation Settings','geomvert',seg_ver_geometry,'skipline',skipline_panel);
if ~strcmp (strhalt_seg,'')
grp_proc_info = beapp_gui_seg_subfunction_save_inputs (current_sub_panel,resstruct_seg_settings,grp_proc_info);
end
% change available panels based on user data type selection
if seg_sub_panel_ctr ==1
[seg_sub_panel_list, show_next_button] = adjust_seg_panel_list (grp_proc_info.src_data_type);
end
[strhalt_seg_out, seg_sub_panel_ctr, show_back_button, show_next_button] =...
beapp_gui_navigate_subpanels(strhalt_seg, seg_sub_panel_ctr,length(seg_sub_panel_list));
end
end
function [seg_sub_panel_list, show_next_button] = adjust_seg_panel_list (src_data_type)
% change available panels based on user data type selection
switch src_data_type
case 1 % baseline
seg_sub_panel_list = {'seg_general','seg_baseline'};
case 2 % event-related
seg_sub_panel_list = {'seg_general', 'seg_evt_stm_on_off_info','seg_evt_condition_codes'};
case 3 % conditioned baseline
seg_sub_panel_list = {'seg_general', 'seg_evt_stm_on_off_info', 'seg_evt_condition_codes'};
end
if length(seg_sub_panel_list) ==1
show_next_button = 'off';
else
show_next_button = 'on';
end
end
|
github
|
lcnbeapp/beapp-master
|
supergui_mod_for_beapp.m
|
.m
|
beapp-master/functions/gui_functions/supergui_mod_for_beapp.m
| 22,954 |
utf_8
|
3e46e61716eacad4934a4dfad6cf5a28
|
% supergui_mod_for_beapp
% very slightly modified version of supergui (function written for eeglab)
% adds options for:
% 'backcolor' - background color for GUI
% buttoncolor - button color
% 'button_fontsize' - fontsize on buttons
% removes dependencies on EEGLAB specific parameters
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001-
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
% supergui() - a comprehensive gui automatic builder. This function help
% to create GUI very fast without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves into the predefined
% locations. It is especially usefull for figure where you
% intend to put text button and descriptions.
%
% Usage:
% >> [handles, height, allhandles ] = ...
% supergui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'fig' - figure handler, if not given, create a new figure.
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the following
% manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geomhoriz' - integer vector or cell array of numerical vectors describing the
% geometry of the elements in the figure.
% - if integer vector, vector length is the number of rows and vector
% values are the number of 'uilist' elements in each row.
% For example, [2 3 2] means that the
% figures will have 3 rows, with 2 elements in the first
% and last row and 3 elements in the second row.
% - if cell array, each vector describes the relative widths
% of items in each row. For example, { [2 8] [1 2 3] } which means
% that figures will have 2 rows, the first one with 2
% elements of relative width 2 and 8 (20% and 80%). The
% second row will have 3 elements of relative size 1, 2
% and 3 (1/6 2/6 and 3/6).
% 'geomvert' - describting geometry for the rows. For instance
% [1 2 1] means that the second row will be twice the height
% of the other ones. If [], all the lines have the same height.
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% 'borders' - [left right top bottom] GUI internal borders in normalized
% units (0 to 1). Default values are
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'inseth' - horizontal space between elements. Default is 2%
% of window size.
% 'insetv' - vertical space between elements. Default is 2%
% of window height.
% 'spacing' - [horiz vert] spacing in normalized units. Default
% 'spacingtype' - ['absolute'|'proportional'] abolute means that the
% spacing values are fixed. Proportional means that they
% depend on the number of element in a line.
% 'minwidth' - [integer] minimal width in pixels. Default is none.
% 'screenpos' - [x y] position of the right top corner of the graphic
% interface. 'center' may also be used to center the GUI on
% the screen.
% 'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI.
% Default is 'off'.
%
% Hint:
% use 'print -mfile filemane' to save a matlab file of the figure.
%
% Output:
% handles - all the handles of the elements (in the same order as the
% uilist input).
% height - adviced height for the figure (so the text look nice).
% allhandles - all the handles in object format
%
% Example:
% figure;
% supergui( 'geomhoriz', { 1 1 }, 'uilist', { ...
% { 'style', 'radiobutton', 'string', 'radio' }, ...
% { 'style', 'pushbutton' , 'string', 'push' } } );
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001-
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [handlers, outheight, allhandlers] = supergui_mod_for_beapp(varargin)
% handlers cell format
% allhandlers linear format
handlers = {};
outheight = 0;
if nargin < 2
help supergui;
return;
end;
% get version and
% set additional parameters
% -------------------------
v = version;
indDot = find(v == '.');
versnum = str2num(v(1:indDot(2)-1));
if versnum >= 7.14
addParamFont = { 'fontsize' 12 };
else addParamFont = { };
end;
warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'fig' varargin{1} 'geomhoriz' varargin{2} ...
'geomvert' varargin{3} 'uilist' varargin(4:end) };
end
g = finputcheck(options, { 'geomhoriz' 'cell' [] {};
'fig' '' [] 0;
'geom' 'cell' [] {};
'uilist' 'cell' [] {};
'title' 'string' [] '';
'userdata' '' [] [];
'adjustbuttonwidth' 'string' { 'on' 'off' } 'off';
'geomvert' 'real' [] [];
'screenpos' { 'real' 'string' } [] [];
'horizontalalignment' 'string' { 'left','right','center' } 'left';
'minwidth' 'real' [] 10;
'borders' 'real' [] [0.05 0.04 0.07 0.06];
'spacing' 'real' [] [0.02 0.01];
'inseth' 'real' [] 0.02; % x border absolute (5% of width)
'insetv' 'real' [] 0.02 ;
'backcolor' 'real' [] [0.8590, 1.0000, 1.0000];
'button_fontsize' 'real' [] 25;
'buttoncolor' 'real' [] [0.6000 0.8000 1.0000] ;}, 'supergui');
if isstr(g), error(g); end
if ~isempty(g.geomhoriz)
maxcount = sum(cellfun('length', g.geomhoriz));
if maxcount ~= length(g.uilist)
warning('Wrong size for ''geomhoriz'' input');
end;
if ~isempty(g.geomvert)
if length(g.geomvert) ~= length(g.geomhoriz)
warning('Wrong size for ''geomvert'' input');
end;
end;
g.insetv = g.insetv/length(g.geomhoriz);
end;
if ~isempty(g.geom)
if length(g.geom) ~= length(g.uilist)
warning('Wrong size for ''geom'' input');
end;
maxcount = length(g.geom);
end;
% create new figure
% -----------------
if g.fig == 0
g.fig = figure('visible','off');
end
% converting the geometry formats
% -------------------------------
if ~isempty(g.geomhoriz) & ~iscell( g.geomhoriz )
oldgeom = g.geomhoriz;
g.geomhoriz = {};
for row = 1:length(oldgeom)
g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) };
end;
end
if isempty(g.geomvert)
g.geomvert = ones(1, length(g.geomhoriz));
end
% converting to the new format
% ----------------------------
if isempty(g.geom)
count = 1;
incy = 0;
sumvert = sum(g.geomvert);
maxhoriz = 1;
for row = 1:length(g.geomhoriz)
incx = 0;
maxhoriz = max(maxhoriz, length(g.geomhoriz{row}));
ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row});
for column = 1:length(g.geomhoriz{row})
g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] };
incx = incx+g.geomhoriz{row}(column)*ratio;
count = count+1;
end;
incy = incy+g.geomvert(row);
end;
g.borders(1:2) = g.borders(1:2)/maxhoriz*5;
g.borders(3:4) = g.borders(3:4)/sumvert*10;
g.spacing(1) = g.spacing(1)/maxhoriz*5;
g.spacing(2) = g.spacing(2)/sumvert*10;
end;
% disp new geometry
% -----------------
if 0
fprintf('{ ...\n');
for index = 1:length(g.geom)
fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ...
g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2));
end;
fprintf('};\n');
end;
% get axis coordinates
% --------------------
try
set(g.fig, 'menubar', 'none', 'numbertitle', 'off');
catch
end
pos = [0 0 1 1]; % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y
axis('off');
% creating guis
% -------------
row = 1; % count the elements
column = 1; % count the elements
factmultx = 0;
factmulty = 0; %zeros(length(g.geomhoriz));
for counter = 1:maxcount
% init
clear rowhandle;
gm = g.geom{counter};
[posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing);
try
currentelem = g.uilist{ counter };
catch
fprintf('Warning: not all boxes were filled\n');
return;
end;
if ~isempty(currentelem)
% decode metadata
% ---------------
if strcmpi(currentelem{1}, 'link2lines'),
currentelem(1) = [];
hf1 = 3.6/2-0.3;
hf2 = 0.7/2-0.3;
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = 0;
else
if strcmpi(currentelem{1}, 'width'),
curwidth = currentelem{2};
currentelem(1:2) = [];
else curwidth = 0;
end;
if strcmpi(currentelem{1}, 'align'),
align = currentelem{2};
currentelem(1:2) = [];
else align = 'right';
end;
if strcmpi(currentelem{1}, 'stickto'),
stickto = currentelem{2};
currentelem(1:2) = [];
else stickto = 'none';
end;
if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2;
else addvert = 0;
end;
if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = [];
else heightfactor = 1;
end;
% position adjustment depending on GUI type
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu')
posy = posy-height/10;
end;
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'text')
posy = posy+height/5;
end;
if strcmpi(currentelem{1}, 'function'),
% property grid argument
panel = uipanel('Title','','FontSize',g.button_fontsize,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q);
allhandlers{counter} = arg_guipanel(panel, currentelem{:});
else
if strcmpi(currentelem{2}, 'uitable'),
allhandlers{counter} = uitable(g.fig,'unit', 'normalized', 'position', ...
[posx posy+addvert width height*heightfactor].*s+q, currentelem{3:end}, addParamFont{:});
style = 'uitable';
else
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:});
style = get(allhandlers{counter}, 'style');
end
% this simply compute a factor so that all uicontrol will be visible
% ------------------------------------------------------------------
set( allhandlers{counter}, 'units', 'pixels');
curpos = get(allhandlers{counter}, 'position');
curext = get(allhandlers{counter}, 'extent');
if curwidth ~= 0
curwidth = curwidth/((factmultx-1)/1.85+1);
if strcmpi(align, 'right')
curpos(1) = curpos(1)+curpos(3)-curwidth;
elseif strcmpi(align, 'center')
curpos(1) = curpos(1)+curpos(3)/2-curwidth/2;
end;
set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]);
if strcmpi(stickto, 'on')
set( allhandlers{counter-1}, 'units', 'pixels');
curpos2 = get(allhandlers{counter-1}, 'position');
set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]);
set( allhandlers{counter-1}, 'units', 'normalized');
end;
curext(3) = curwidth;
end;
set( allhandlers{counter}, 'units', 'normalized');
end;
if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on'))
%tmp = curext(3)/curpos(3);
%if tmp > 3*factmultx && factmultx > 0, adsfasd; end;
factmultx = max(factmultx, curext(3)/curpos(3));
if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end;
end;
if ~strcmp(style, 'listbox')
factmulty = max(factmulty, curext(4)/curpos(4));
end;
% Uniformize button text aspect (first letter must be upercase)
% -----------------------------
if strcmp(style, 'pushbutton') && ~strcmp(get(allhandlers{counter},'type'),'uitable')
tmptext = get(allhandlers{counter}, 'string');
if length(tmptext) > 1
if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS')
tmptext = lower(tmptext);
try, tmptext(1) = upper(tmptext(1)); catch, end;
end;
end;
set(allhandlers{counter}, 'string', tmptext);
end;
end;
else
allhandlers{counter} = 0;
end;
end;
% adjustments
% -----------
factmultx = factmultx*1.02;% because some text was still hidden
%factmultx = factmultx*1.2;
if factmultx < 0.1
factmultx = 0.1;
end;
% for MAC (magnify figures that have edit fields)
% -------
warning off;
try,
comp = computer;
if length(comp) > 2 && strcmpi(comp(1:3), 'MAC')
factmulty = factmulty*1.5;
elseif ~isunix % windows
factmulty = factmulty*1.08;
end;
catch, end;
factmulty = factmulty*0.9; % global shinking
warning on;
% scale and replace the figure in the screen
% -----------------------------------------
pos = get(g.fig, 'position');
if factmulty > 1
pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty);
end;
pos(1) = pos(1)+pos(3)*(1-factmultx)/2;
pos(3) = max(pos(3)*factmultx, g.minwidth);
pos(4) = pos(4)*factmulty;
set(g.fig, 'position', pos);
% vertical alignment to bottom for text (isnumeric by ishanlde was changed here)
% ---------------------------------------
for index = 1:length(allhandlers)
if allhandlers{index} ~= 0 && ishandle(allhandlers{index})
if ~strcmp(get(allhandlers{index},'type'),'uitable')
if strcmp(get(allhandlers{index}, 'style'), 'text')
set(allhandlers{index}, 'unit', 'pixel');
curpos = get(allhandlers{index}, 'position');
curext = get(allhandlers{index}, 'extent');
set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]);
set(allhandlers{index}, 'unit', 'normalized');
end;
else
figpos = get(g.fig, 'position');
set(allhandlers{index}, 'unit', 'pixel');
curpos = get(allhandlers{index}, 'position');
curext = get(allhandlers{index}, 'extent');
% center uitables in figures (assumes on their own line)
set(allhandlers{index}, 'position', [(figpos(3)/2)-curext(3)/2 curpos(2)-4 curext(3) curext(4)]);
set(allhandlers{index}, 'unit', 'normalized');
end;
end;
end;
% setting defaults colors
%------------------------
%try, icadefs;
%catch,
GUIBACKCOLOR = g.backcolor;
GUIPOPBUTTONCOLOR = g.buttoncolor;
GUITEXTCOLOR = [0 0 0];
GUIPOPMENUCOLOR = [1 1 1];
%end;
numobjects = cellfun(@ishandle, allhandlers); % (isnumeric by ishanlde was changed here)
allhandlersnum = [ allhandlers{numobjects} ];
hh = findobj(allhandlersnum, 'parent', g.fig, 'style', 'text');
set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', g.horizontalalignment);
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
try
set(g.fig, 'color',GUIBACKCOLOR );
catch
end
set(hh, 'horizontalalignment', g.horizontalalignment);
hh = findobj(allhandlersnum, 'style', 'edit');
set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right');
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'pushbutton');
comp = computer;
if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
end;
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'popupmenu');
set(hh, 'backgroundcolor', GUIPOPMENUCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'checkbox');
set(hh, 'backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'listbox');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'radio');
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(g.fig, 'visible', 'on');
% screen position
% ---------------
if ~isempty(g.screenpos)
pos = get(g.fig, 'position');
if isnumeric(g.screenpos)
set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]);
else
screenSize = get(0, 'screensize');
pos(1) = (screenSize(3)-pos(3))/2;
pos(2) = (screenSize(4)-pos(4))/2+pos(4);
set(g.fig, 'position', pos);
end;
end;
% set userdata and title
% ----------------------
if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end;
if ~isempty(g.title ), set(g.fig, 'name', g.title ); end;
return;
function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing);
coord2 = coord1+sz;
borders(1:2) = borders(1:2)-spacing(1);
borders(3:4) = borders(3:4)-spacing(2);
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+spacing(1)/2;
width = max(posx2-posx-spacing(1), 0.001);
height = max(posy2-posy-spacing(2), 0.001);
posy = max(0, 1-posy2)+spacing(2)/2;
% add border
posx = posx*(1-borders(1)-borders(2))+borders(1);
posy = posy*(1-borders(3)-borders(4))+borders(4);
width = width*( 1-borders(1)-borders(2));
height = height*(1-borders(3)-borders(4));
function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz);
coord2 = coord1+sz;
horiz_space = 0.05/geom1;
vert_space = 0.05/geom2;
horiz_border = min(0.1, 1/geom1)-horiz_space;
vert_border = min(0.2, 1.5/geom2)-vert_space;
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+horiz_space/2;
width = max(posx2-posx-horiz_space, 0.001);
height = max(posy2-posy- vert_space, 0.001);
posy = max(0, 1-posy2)+vert_space/2;
% add border
posx = posx*(1-horiz_border)+horiz_border/2;
posy = posy*(1- vert_border)+vert_border/2;
width = width*(1-horiz_border);
height = height*(1-vert_border);
% posx = coord1(1)/geom1+horiz_border*1/geom1/2;
% posy = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% posx2 = coord2(1)/geom1+horiz_border*1/geom1/2;
% posy2 = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% width = posx2-posx;
% height = posy-posy2;
%h = axes('unit', 'normalized', 'position', [ posx posy width height ]);
%h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
|
github
|
lcnbeapp/beapp-master
|
unique_bc.m
|
.m
|
beapp-master/functions/gui_functions/unique_bc.m
| 738 |
utf_8
|
e3e09500a6ce1840521829a4f979ca39
|
% unique_bc - unique backward compatible with Matlab versions prior to 2013a
% also see eeglab ()
function [C,IA,IB] = unique_bc(A,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = unique(A,varargin{:},'legacy');
if errorFlag
[C2,IA2] = unique(A,varargin{:});
if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)
warning('backward compatibility issue with call to unique function');
end;
end;
else
[C,IA,IB] = unique(A,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
beapp_gui_hide_unneeded_inputs.m
|
.m
|
beapp-master/functions/gui_functions/beapp_gui_hide_unneeded_inputs.m
| 1,186 |
utf_8
|
19a1c99d6d2a8deca671823207643f0c
|
% turn corresponding inputs invisible in GUI if checkbox is selected/field
% is set to a specific value
% checkbox_tag is the tag for the primary field
% other_input_tags are corresponding tags to mark visible or invisible
% checkbox_on_val ('On' or 'Off')-- turn inputs visible or invisible if
% checkbox/field is expected value
% comp_val is comparison value for field
function beapp_gui_hide_unneeded_inputs(checkbox_tag, other_input_tags,checkbox_on_val,comp_val)
% confirm checkbox is on or off
if isequal(comp_val,'NoCompVal')
checkbox_sel = get(findobj('tag',checkbox_tag),'Value');
else % or check if desired element is set to a specific value
checkbox_sel = isequal(get(findobj('tag',checkbox_tag),'Value'),comp_val);
end
% set visibility dependent on element value
if (checkbox_sel && strcmp(checkbox_on_val,'On')) || (~checkbox_sel && strcmp(checkbox_on_val,'Off'))
set_vis_str = 'On';
elseif (~checkbox_sel && strcmp(checkbox_on_val,'On')) || (checkbox_sel && strcmp(checkbox_on_val,'Off'))
set_vis_str = 'Off';
end
for curr_input_tag = 1:length(other_input_tags)
set(findobj('tag',other_input_tags{curr_input_tag}), 'Visible', set_vis_str);
end
|
github
|
lcnbeapp/beapp-master
|
beapp_gui_add_delete_rename_condition_columns.m
|
.m
|
beapp-master/functions/gui_functions/beapp_gui_add_delete_rename_condition_columns.m
| 3,625 |
utf_8
|
f8e81d1e36355aa981e8201bf3c29d4e
|
% function to automatically add, delete, and rename condition columns
% Inputs:
% seg_evt_table is the GUI table with the list of conditions currently
% selected
% add_del_ren is a tag generated by the associated button push for adding,
% deleting, or renaming
function beapp_gui_add_delete_rename_condition_columns (seg_evt_table,add_del_ren)
scrsz = get(groot,'ScreenSize');
win_width = scrsz(3)/4;
switch add_del_ren
case 'add'
empty_10_cel = cell(10,1);
empty_10_cel(:) = deal({''});
seg_opt_button_list = [{{'style','text','string','Enter Names of Conditions to Add Below'}},...
{{'style','uitable','data', empty_10_cel,'tag','seg_evt_tag_table_cond_add', ...
'ColumnFormat',{'char'},'ColumnEditable',[true],'ColumnName','New Conditions'}}];
seg_opt_button_geometry = {1 1};
seg_opt_ver_geometry= [1 5];
case 'delete'
seg_opt_button_list = [{{'style','text','string','Delete Segment Conditions'}},...
{{'style','listbox', 'string', seg_evt_table.ColumnName,'max',100,'min',1,'tag','seg_evt_tag_table_cond_del_select'}}];
seg_opt_button_geometry = {1 1};
seg_opt_ver_geometry= [1 5];
case 'rename'
all_condition_names = horzcat(seg_evt_table.ColumnName,seg_evt_table.ColumnName);
seg_opt_button_list = [{{'style','text','string','Rename Segment Conditions'}},...
{{'style','uitable','data', all_condition_names,'tag','seg_evt_tag_table_cond_rename',...
'ColumnFormat',{'char','char'},'ColumnEditable',[false true],...
'ColumnName',{'Current_Condition_Names', 'Desired_Condition_Names'}}}];
seg_opt_button_geometry = {1 1};
seg_opt_ver_geometry= [1 5];
end
[~, ~, strhalt_seg_opt_evt, resstruct_seg_opt_evt, ~] = inputgui_mod_for_beapp('geometry',seg_opt_button_geometry ,...
'uilist',seg_opt_button_list,'popoutpanel',1,...
'title','Rename Conditions for Segmentation','minwidth',win_width,...
'geomvert',seg_opt_ver_geometry,'skipline','on','tag','seg_evt_cond_del_rename_add');
if ~isempty(strhalt_seg_opt_evt)
seg_table_handle = findobj('tag','seg_evt_tag_table');
switch add_del_ren
case 'add'
add_cond_names = resstruct_seg_opt_evt.seg_evt_tag_table_cond_add.data;
add_cond_names(cellfun('isempty',add_cond_names)) = [];
add_cond_formats = cell(1,length(add_cond_names));
add_cond_formats(:) = deal({'numeric'});
starter_data_to_add = cell(size(seg_table_handle.Data,1),length(add_cond_names));
seg_table_handle.Data = [seg_table_handle.Data,starter_data_to_add];
seg_table_handle.ColumnName = [seg_table_handle.ColumnName; add_cond_names];
seg_table_handle.ColumnFormat =[seg_table_handle.ColumnFormat,add_cond_formats];
seg_table_handle.ColumnEditable= [seg_table_handle.ColumnEditable, true(length(add_cond_names))];
case 'delete'
seg_table_handle.ColumnName(resstruct_seg_opt_evt.seg_evt_tag_table_cond_del_select)=[];
seg_table_handle.Data(:,resstruct_seg_opt_evt.seg_evt_tag_table_cond_del_select)=[];
seg_table_handle.ColumnFormat(resstruct_seg_opt_evt.seg_evt_tag_table_cond_del_select)=[];
seg_table_handle.ColumnEditable(resstruct_seg_opt_evt.seg_evt_tag_table_cond_del_select)=[];
case 'rename'
seg_table_handle.ColumnName = resstruct_seg_opt_evt.seg_evt_tag_table_cond_rename.data(:,2);
end
end
|
github
|
lcnbeapp/beapp-master
|
beapp_gui_add_nets_to_library.m
|
.m
|
beapp-master/functions/gui_functions/beapp_gui_add_nets_to_library.m
| 1,627 |
utf_8
|
f35bdf6ea3bb30681768cad2df5ec3f6
|
% gui wrapper for adding nets to net library
function beapp_gui_add_nets_to_library(grp_proc_info_in,net_disp_table_tag)
empty_10_cell = cell(10,1);
empty_10_cell(:) = deal({''});
button_list=[{{'style','text','string', ...
'Enter exact names of new nets/sensor layouts to add below'}},...
{{'style','uitable','data',empty_10_cell,'tag','new_net_name_table', ...
'ColumnFormat',{'char'},'ColumnEditable',true,'ColumnName',{'SensorLayoutNames'}}}];
button_geometry = {1 1};
button_ver_geometry = [1 6];
scrsz = get(groot,'ScreenSize');
win_width = scrsz(3)/4;
% make figure for module advanced settings
[~, ~, strhalt_nets, resstruct_nets, ~] = inputgui_mod_for_beapp('geometry',button_geometry ,...
'uilist',button_list,'title','Add New Sensor Layouts','geomvert',button_ver_geometry,'minwidth',win_width,...
'tag','new_net_add_fig');
% if user saves the inputs
if ~strcmp (strhalt_nets,'')
% delete empty rows
non_empty_inds = cellfun(@ (x) ~isempty(x),resstruct_nets.new_net_name_table.data(:,1),'UniformOutput',1);
if any (non_empty_inds)
net_list = resstruct_nets.new_net_name_table.data(non_empty_inds,1);
% call net adding function
netmenuoptions = add_nets_to_library(net_list,grp_proc_info_in.ref_net_library_options,...
grp_proc_info_in.ref_net_library_dir, grp_proc_info_in.ref_eeglab_loc_dir,grp_proc_info_in.name_10_20_elecs);
set(findobj('tag',net_disp_table_tag),'ColumnFormat',{netmenuoptions'});
else
warndlg('No sensor layout names entered, no sensor layouts added to library');
end
end
|
github
|
lcnbeapp/beapp-master
|
reset_beapp_path_defaults.m
|
.m
|
beapp-master/functions/gui_functions/reset_beapp_path_defaults.m
| 1,495 |
utf_8
|
d7e37a60a1827f917eda5bccb6197314
|
% reset beapp ref paths on template load in case the computer has changed
function grp_proc_info = reset_beapp_path_defaults (grp_proc_info)
%% version numbers for BEAPP and packages
grp_proc_info.beapp_ver={'BEAPP_v4_1'};
grp_proc_info.eeglab_ver = {'eeglab14_1_2b'};
grp_proc_info.fieldtrip_ver = {'fieldtrip-20160917'};
grp_proc_info.beapp_root_dir = {fileparts(which('set_beapp_def.m'))}; %sets the directory to the BEAPP code assuming that it is in same directory as set_beapp_def
%% paths for packages and tables
grp_proc_info.beapp_ft_pname={[grp_proc_info.beapp_root_dir{1},filesep,'Packages',filesep,grp_proc_info.eeglab_ver{1},filesep,grp_proc_info.fieldtrip_ver{1}]};
grp_proc_info.beapp_format_mff_jar_lib = [grp_proc_info.beapp_root_dir{1} filesep 'reference_data' filesep 'MFF-1.2.jar']; %the java class file needed when reading mff source files
grp_proc_info.ref_net_library_dir=[grp_proc_info.beapp_root_dir{1},filesep,'reference_data',filesep,'net_library'];
grp_proc_info.ref_net_library_options = ([grp_proc_info.beapp_root_dir{1},filesep,'reference_data',filesep,'net_library_options.mat']);
grp_proc_info.ref_eeglab_loc_dir = [grp_proc_info.beapp_root_dir{1},filesep, 'Packages',filesep,grp_proc_info.eeglab_ver{1},filesep, 'sample_locs'];
grp_proc_info.ref_def_template_folder = [fileparts(mfilename('fullpath')) filesep, 'run_templates'];
grp_proc_info.rerun_file_info_table =[grp_proc_info.beapp_root_dir{1} filesep 'user_inputs',filesep,'rerun_fselect_table.mat'];
|
github
|
lcnbeapp/beapp-master
|
adv_inputgui_mod_for_beapp.m
|
.m
|
beapp-master/functions/gui_functions/adv_inputgui_mod_for_beapp.m
| 19,504 |
utf_8
|
e7b7c964451d793642d90ac60df6dba3
|
% adv_inputgui_mod_for_beapp() - Modified very slightly from EEGLAB's inputgui
% to allow for run flexibility when generating advanced input windows and
% generation of a few more kinds of elements
% inputgui() - A comprehensive gui automatic builder. This function helps
% to create GUI very quickly without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves in the predefined
% locations. It is especially useful for figures in which
% you intend to put text buttons and descriptions.
%
% Usage:
% >> [ outparam ] = inputgui( 'key1', 'val1', 'key2', 'val2', ... );
% >> [ outparam userdat strhalt outstruct] = ...
% inputgui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the
% following manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geometry' - cell array describing horizontal geometry. This corresponds
% to the supergui function input 'geomhoriz'
% 'geomvert' - vertical geometry argument, this argument is passed on to
% the supergui function
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% Uitables can also be created using this function with the following format:
% {{'style','uitable','data', data,...
% 'ColumnEditable',[false, true],'ColumnName',{'Headers','Headers2'},...
% 'ColumnFormat',{'char','logical'},'tag','table_name'}}
% 'helpcom' - optional help command
% 'helpbut' - text for help button
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'mode' - ['normal'|'noclose'|'plot' fignumber]. Either wait for
% user to press ok_adv or CANCEL ('normal'), return without
% closing window input ('noclose'), only draw the gui ('plot')
% or process an existing window which number is given as
% input (fignumber). Default is 'normal'.
% 'eval' - [string] command to evaluate at the end of the creation
% of the GUI but before waiting for user input.
% 'screenpos' - see supergui.m help message.
% 'skipline' - ['on'|'off'] skip a row before the "ok_adv" and "Cancel"
% button. Default is 'on'.
% 'tag' -- figure tag. default is 'subsection_template_fig';...
% 'buttoncolor' - figure button color (def [0.6000 0.8000 1.0000])
% 'backcolor' - figure background color (def [0.8590, 1.0000, 1.0000];)...
% 'nextbutton' - {'on','off'} def 'off' -- add a next button to figure;...
% 'backbutton' - {'on','off'} def 'off' -- add a back button to figure;...
% 'nextbuttoncall' - button call for next button
% 'backbuttoncall' - button call for back button
% 'mutetagwarn' -- mute warnings for generating a figure with the same
% tag as another figure def = 0
%
% Output:
% outparam - list of outputs. The function scans all lines and
% add up an output for each interactive uicontrol, i.e
% edit box, radio button, checkbox and listbox.
% userdat - 'userdata' value of the figure.
% strhalt - the function returns when the 'userdata' field of the
% button with the tag 'ok_adv' or is modified. This returns the
% new value of this field.
% Possible values are:
% 'retuninginputui_adv' if user selects Save button
% 'retuninginputui_adv_next' if user selects next button
% 'retuninginputui_adv_back' if user selects back button
% '' if user selects Cancel
% outstruct - returns outputs as a structure (only tagged ui controls
% are considered). The field name of the structure is
% the tag of the ui and contain the ui value or string.
% instruct - resturn inputs provided in the same format as 'outstruct'
% This allow to compare in/outputs more easy.
%
% Note: the function also adds three buttons at the bottom of each
% interactive windows: 'CANCEL', 'HELP' (if callback command
% is provided) and 'ok_adv'.
%
% Example:
% res = inputgui('geometry', { 1 1 }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% res = inputgui('geom', { {2 1 [0 0] [1 1]} {2 1 [1 0] [1 1]} }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 1 Feb 2002
%
% See also: supergui(), eeglab()
% Copyright (C) Arnaud Delorme, CNL/Salk Institute, 27 Jan 2002, [email protected]
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result, userdat, strhalt, resstruct, instruct] = adv_inputgui_mod_for_beapp(varargin);
if nargin < 2
help inputgui;
return;
end;
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'geometry' 'uilist' 'helpcom' 'title' 'userdata' 'mode' 'geomvert' };
options = { options{1:length(varargin)}; varargin{:} };
options = options(:)';
end;
% checking inputs
% ---------------
g = finputcheck(options, { 'geom' 'cell' [] {}; ...
'geometry' {'cell','integer'} [] []; ...
'uilist' 'cell' [] {}; ...
'helpcom' { 'string','cell' } { [] [] } ''; ...
'title' 'string' [] ''; ...
'eval' 'string' [] ''; ...
'helpbut' 'string' [] 'Help'; ...
'skipline' 'string' { 'on' 'off' } 'on'; ...
'addbuttons' 'string' { 'on' 'off' } 'on'; ...
'userdata' '' [] []; ...
'getresult' 'real' [] []; ...
'minwidth' 'real' [] 200; ...
'screenpos' '' [] []; ...
'mode' '' [] 'normal'; ...
'horizontalalignment' 'string' { 'left','right','center' } 'left';...
'geomvert' 'real' [] []; ... % start beapp additions
'buttoncolor' 'real' [] [0.6000 0.8000 1.0000];...
'backcolor' 'real' [] [0.8590, 1.0000, 1.0000];...
'nextbutton' 'string' {'on','off'} 'off';...
'backbutton' 'string' {'on','off'} 'off';...
'nextbuttoncall' 'string' [] '';...
'backbuttoncall' 'string' [] '';...
'tag' 'string' [] 'subsection_template_fig';...
'mutetagwarn' 'real' [0, 1] 0;...
'popoutpanel' 'real' [0, 1] 0;...
}, 'inputgui');
if isstr(g), error(g); end;
if isempty(g.getresult)
if isstr(g.mode)
fig = figure('visible', 'off');
set(fig, 'name', g.title);
set(fig, 'userdata', g.userdata);
if ~g.mutetagwarn % if not part of a current panel progression
% beapp add start
if ~isempty(findobj('tag',g.tag'))
if g.popoutpanel == 1
answer = questdlg('You have another settings panel for this module open. Would you like to close that panel and open the selected settings?',...
'Multiple Module Settings Open','Go Back','Yes,close the other settings and continue','Go Back');
else
answer = questdlg('You have settings for another module open. Would you like to close those and open the selected settings?',...
'Multiple Module Settings Open','Go Back','Yes,close the other settings and continue','Go Back');
end
switch answer
case 'Go Back'
result = [];
userdat =[];
strhalt = '';
resstruct = [];
instruct =[];
% move open window to center
movegui(findobj('tag',g.tag'),'center');
uistack(findobj('tag',g.tag'),'top');
return;
case 'Yes,close the other settings and continue'
close(findobj('tag',g.tag));
end
end
end
set(fig, 'tag',g.tag);
% beapp add end
if ~iscell( g.geometry )
oldgeom = g.geometry;
g.geometry = {};
for row = 1:length(oldgeom)
g.geometry = { g.geometry{:} ones(1, oldgeom(row)) };
end;
end
% skip a line
if strcmpi(g.skipline, 'on'),
g.geometry = { g.geometry{:} [1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} {1 g.geom{1}{2} [0 g.geom{1}{2}-2] [1 1] } };
end;
g.uilist = { g.uilist{:}, {} };
end;
% beapp add -- add next and back buttons to geometry counts
if strcmpi(g.nextbutton, 'on') || strcmpi(g.backbutton, 'on'),
% add a row with 4 slots
g.geometry = { g.geometry{:} [1 1 1 1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} ...
{4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } };
end;
% fill in empty space for first 2 slots
g.uilist = { g.uilist{:}, {} {} };
if strcmpi(g.backbutton, 'on'),
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Back', 'tag' 'back' 'callback',...
'set(findobj(''parent'', gcf, ''tag'', ''ok_adv''), ''userdata'', ''retuninginputui_adv_back'');' } };
else
g.uilist = { g.uilist{:}, {'width' 80 'style','text','string','', 'tag', 'back'} };
end
if strcmpi(g.nextbutton, 'on'),
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'next', 'string', 'Next',...
'callback', 'set(findobj(''parent'', gcf, ''tag'', ''ok_adv''), ''userdata'', ''retuninginputui_adv_next'');' } };
else
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'text', 'tag', 'next', 'string', ''} };
end
end;
% add buttons
if strcmpi(g.addbuttons, 'on'),
g.geometry = { g.geometry{:} [1 1 1 1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} ...
{4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } };
end;
if ~isempty(g.helpcom)
if ~iscell(g.helpcom)
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', g.helpbut, 'tag', 'help', 'callback', g.helpcom } {} };
else
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'Help gui', 'callback', g.helpcom{1} } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'More help', 'callback', g.helpcom{2} } };
end;
else
g.uilist = { g.uilist{:}, {} {} };
end;
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok_adv', 'string', 'Save', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui_adv'');' } };
end;
% add the three buttons (CANCEL HELP ok_adv) at the bottom of the GUI
% ---------------------------------------------------------------
if ~isempty(g.geom)
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geom', g.geom, ...
'uilist', g.uilist, 'screenpos', g.screenpos,'backcolor',g.backcolor,'buttoncolor',g.buttoncolor,'horizontalalignment',g.horizontalalignment );
elseif isempty(g.geomvert)
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, ...
'uilist', g.uilist, 'screenpos', g.screenpos,'backcolor',g.backcolor,'buttoncolor',g.buttoncolor,'horizontalalignment',g.horizontalalignment );
else
if strcmpi(g.skipline, 'on'), g.geomvert = [g.geomvert(:)' 1]; end;
if strcmpi(g.addbuttons, 'on'),g.geomvert = [g.geomvert(:)' 1]; end;
if strcmpi(g.nextbutton, 'on')||strcmpi(g.backbutton, 'on'),g.geomvert = [g.geomvert(:)' 1]; end;
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, ...
'uilist', g.uilist, 'screenpos', g.screenpos, 'geomvert', g.geomvert(:)','backcolor',g.backcolor,'buttoncolor',g.buttoncolor, 'horizontalalignment',g.horizontalalignment );
end;
else
fig = g.mode;
set(findobj('parent', fig, 'tag', 'ok_adv'), 'userdata', []);
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
% evaluate command before waiting?
% --------------------------------
if ~isempty(g.eval), eval(g.eval); end;
instruct = outstruct(allobj); % Getting default values in the GUI.
% create figure and wait for return
% ---------------------------------
if isstr(g.mode) & (strcmpi(g.mode, 'plot') | strcmpi(g.mode, 'return') )
if strcmpi(g.mode, 'plot')
return; % only plot and returns
end;
else
waitfor( findobj('parent', fig, 'tag', 'ok_adv'), 'userdata');
end;
else
fig = g.getresult;
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
result = {};
userdat = [];
strhalt = '';
resstruct = [];
if ~(ishandle(fig)), return; end % Check if figure still exist
% output parameters
% -----------------
strhalt= get(findobj('parent', fig, 'tag', 'ok_adv'), 'userdata');
[resstruct,result] = outstruct(allobj); % Output parameters
userdat = get(fig, 'userdata');
% if nargout >= 4
% resstruct = myguihandles(fig, g);
% end;
if isempty(g.getresult) && isstr(g.mode) && ( strcmp(g.mode, 'normal') || strcmp(g.mode, 'return') )
% if (~strcmp(strhalt, 'retuninginputui_adv_back') && ~strcmp(strhalt, 'retuninginputui_adv_next'))
close(fig);
% end
end;
drawnow; % for windows
% function for gui res (deprecated)
% --------------------
% function g = myguihandles(fig, g)
% h = findobj('parent', fig);
% if ~isempty(get(h(index), 'tag'))
% try,
% switch get(h(index), 'style')
% case 'edit', g = setfield(g, get(h(index), 'tag'), get(h(index), 'string'));
% case { 'value' 'radio' 'checkbox' 'listbox' 'popupmenu' 'radiobutton' }, ...
% g = setfield(g, get(h(index), 'tag'), get(h(index), 'value'));
% end;
% catch, end;
% end;
function [resstructout, resultout] = outstruct(allobj)
counter = 1;
resultout = {};
resstructout = [];
for index=1:length(allobj)
if isnumeric(allobj), currentobj = allobj(index);
else currentobj = allobj{index};
end;
if isnumeric(currentobj) | ~isprop(currentobj,'GetPropertySpecification') % To allow new object handles
try,
objstyle = get(currentobj, 'style');
switch lower( objstyle )
case { 'listbox', 'checkbox', 'radiobutton' 'popupmenu' 'radio' }
resultout{counter} = get( currentobj, 'value');
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
case 'edit'
resultout{counter} = get( currentobj, 'string');
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
end;
catch,
try
switch lower(get(currentobj,'type'))
case 'uitable'
tmp_uitable_holder.data = get(currentobj, 'data');
tmp_uitable_holder.header = get(currentobj, 'ColumnName'); % allows for duplicate names
resultout{counter} = tmp_uitable_holder;
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
% will add in panels and tabs at some point
end
catch
end
end;
else
ps = currentobj.GetPropertySpecification;
resultout{counter} = arg_tovals(ps,false);
count = 1;
while isfield(resstructout, ['propgrid' int2str(count)])
count = count + 1;
end;
resstructout = setfield(resstructout, ['propgrid' int2str(count)], arg_tovals(ps,false));
end;
end;
|
github
|
lcnbeapp/beapp-master
|
finputcheck.m
|
.m
|
beapp-master/functions/gui_functions/finputcheck.m
| 9,133 |
utf_8
|
fe838fecdd60e76a4006a13c7c1b20e4
|
% finputcheck() - check Matlab function {'key','value'} input argument pairs
%
% Usage: >> result = finputcheck( varargin, fieldlist );
% >> [result varargin] = finputcheck( varargin, fieldlist, ...
% callingfunc, mode, verbose );
% Input:
% varargin - Cell array 'varargin' argument from a function call using 'key',
% 'value' argument pairs. See Matlab function 'varargin'.
% May also be a structure such as struct(varargin{:})
% fieldlist - A 4-column cell array, one row per 'key'. The first
% column contains the key string, the second its type(s),
% the third the accepted value range, and the fourth the
% default value. Allowed types are 'boolean', 'integer',
% 'real', 'string', 'cell' or 'struct'. For example,
% {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'}
% {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'}
% callingfunc - Calling function name for error messages. {default: none}.
% mode - ['ignore'|'error'] ignore keywords that are either not specified
% in the fieldlist cell array or generate an error.
% {default: 'error'}.
% verbose - ['verbose', 'quiet'] print information. Default: 'verbose'.
%
% Outputs:
% result - If no error, structure with 'key' as fields and 'value' as
% content. If error this output contain the string error.
% varargin - residual varagin containing unrecognized input arguments.
% Requires mode 'ignore' above.
%
% Note: In case of error, a string is returned containing the error message
% instead of a structure.
%
% Example (insert the following at the beginning of your function):
% result = finputcheck(varargin, ...
% { 'title' 'string' [] ''; ...
% 'percent' 'real' [0 1] 1 ; ...
% 'elecamp' 'integer' [1:10] [] });
% if isstr(result)
% error(result);
% end
%
% Note:
% The 'title' argument should be a string. {no default value}
% The 'percent' argument should be a real number between 0 and 1. {default: 1}
% The 'elecamp' argument should be an integer between 1 and 10 (inclusive).
%
% Now 'g.title' will contain the title arg (if any, else the default ''), etc.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [email protected]
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose )
if nargin < 2
help finputcheck;
return;
end;
if nargin < 3
callfunc = '';
else
callfunc = [callfunc ' ' ];
end;
if nargin < 4
mode = 'do not ignore';
end;
if nargin < 5
verbose = 'verbose';
end;
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
varargnew = {};
% create structure
% ----------------
if ~isempty(vararg)
if isstruct(vararg)
g = vararg;
else
for index=1:length(vararg)
if iscell(vararg{index})
vararg{index} = {vararg{index}};
end;
end;
try
g = struct(vararg{:});
catch
vararg = removedup(vararg, verbose);
try
g = struct(vararg{:});
catch
g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return;
end;
end;
end;
else
g = [];
end;
for index = 1:size(fieldlist,NAME)
% check if present
% ----------------
if ~isfield(g, fieldlist{index, NAME})
g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF});
end;
tmpval = getfield( g, {1}, fieldlist{index, NAME});
% check type
% ----------
if ~iscell( fieldlist{index, TYPE} )
res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ...
fieldlist{index, VALS}, tmpval, callfunc );
if isstr(res), g = res; return; end;
else
testres = 0;
tmplist = fieldlist;
for it = 1:length( fieldlist{index, TYPE} )
if ~iscell(fieldlist{index, VALS})
res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}, tmpval, callfunc );
else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}{it}, tmpval, callfunc );
end;
if ~isstr(res{it}), testres = 1; end;
end;
if testres == 0,
g = res{1};
for tmpi = 2:length(res)
g = [ g 10 'or ' res{tmpi} ];
end;
return;
end;
end;
end;
% check if fields are defined
% ---------------------------
allfields = fieldnames(g);
for index=1:length(allfields)
if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact'))
if ~strcmpi(mode, 'ignore')
g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return;
end;
varargnew{end+1} = allfields{index};
varargnew{end+1} = getfield(g, {1}, allfields{index});
end;
end;
function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc );
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
g = [];
switch fieldtype
case { 'integer' 'real' 'boolean' 'float' },
if ~isnumeric(tmpval) && ~islogical(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return;
end;
if strcmpi(fieldtype, 'boolean')
if tmpval ~=0 && tmpval ~= 1
g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return;
end;
else
if strcmpi(fieldtype, 'integer')
if ~isempty(fieldval)
if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ...
&& (~ismember(tmpval, fieldval))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
else % real or float
if ~isempty(fieldval) && ~isempty(tmpval)
if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2))
g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return;
end;
end;
end;
end;
case 'string'
if ~isstr(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return;
end;
if ~isempty(fieldval)
if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact'))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
case 'cell'
if ~iscell(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return;
end;
case 'struct'
if ~isstruct(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return;
end;
case 'function_handle'
if ~isa(tmpval, 'function_handle')
g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return;
end;
case '';
otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]);
end;
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella, verbose)
% make sure if all the values passed to unique() are strings, if not, exist
%try
[tmp indices] = unique_bc(cella(1:2:end));
if length(tmp) ~= length(cella)/2
myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
%catch
% some elements of cella were not string
% error('some ''key'' values are not string.');
%end;
function myfprintf(verbose, varargin)
if strcmpi(verbose, 'verbose')
fprintf(varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
inputgui_mod_for_beapp.m
|
.m
|
beapp-master/functions/gui_functions/inputgui_mod_for_beapp.m
| 20,526 |
utf_8
|
5dd7ae62aa159e1226cad15b24e4f37c
|
% inputgui_mod_for_beapp() - Modified very slightly from EEGLAB's inputgui
% to allow for run flexibility.
%
% A comprehensive gui automatic builder. This function helps
% to create GUI very quickly without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves in the predefined
% locations. It is especially useful for figures in which
% you intend to put text buttons and descriptions.
%
% Usage:
% >> [ outparam ] = inputgui( 'key1', 'val1', 'key2', 'val2', ... );
% >> [ outparam userdat strhalt outstruct] = ...
% inputgui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the
% following manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geometry' - cell array describing horizontal geometry. This corresponds
% to the supergui function input 'geomhoriz'
% 'geomvert' - vertical geometry argument, this argument is passed on to
% the supergui function
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% Uitables can also be created using this function with the following format:
% {{'style','uitable','data', data,...
% 'ColumnEditable',[false, true],'ColumnName',{'Headers','Headers2'},...
% 'ColumnFormat',{'char','logical'},'tag','table_name'}}
% 'helpcom' - optional help command
% 'helpbut' - text for help button
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'mode' - ['normal'|'noclose'|'plot' fignumber]. Either wait for
% user to press OK or CANCEL ('normal'), return without
% closing window input ('noclose'), only draw the gui ('plot')
% or process an existing window which number is given as
% input (fignumber). Default is 'normal'.
% 'eval' - [string] command to evaluate at the end of the creation
% of the GUI but before waiting for user input.
% 'screenpos' - see supergui.m help message.
% 'skipline' - ['on'|'off'] skip a row before the "OK" and "Cancel"
% button. Default is 'on'.
% 'tag' -- figure tag. default is 'subsection_template_fig';...
% 'buttoncolor' - figure button color (def [0.6000 0.8000 1.0000])
% 'backcolor' - figure background color (def [0.8590, 1.0000, 1.0000];)...
% 'nextbutton' - {'on','off'} def 'off' -- add a next button to figure;...
% 'backbutton' - {'on','off'} def 'off' -- add a back button to figure;...
% 'nextbuttoncall' - button call for next button
% 'backbuttoncall' - button call for back button
% 'mutetagwarn' -- mute warnings for generating a figure with the same
% tag as another figure def = 0
% 'adv_geometry' -- geometry for associated advanced settings
% 'adv_uilist' -- uilist for associated advanced settings
% 'adv_geomvert' 'real' -- vertical geometry for associated advanced
% settings
%
% Output:
% outparam - list of outputs. The function scans all lines and
% add up an output for each interactive uicontrol, i.e
% edit box, radio button, checkbox and listbox.
% userdat - 'userdata' value of the figure.
% strhalt - the function returns when the 'userdata' field of the
% button with the tag 'ok_adv' or is modified. This returns the
% new value of this field.
% Possible values are:
% 'retuninginputui' if user selects Save button
% 'retuninginputui_next' if user selects next button
% 'retuninginputui_back' if user selects back button
% '' if user selects Cancel
% outstruct - returns outputs as a structure (only tagged ui controls
% are considered). The field name of the structure is
% the tag of the ui and contain the ui value or string.
% instruct - resturn inputs provided in the same format as 'outstruct'
% This allow to compare in/outputs more easy.
%
%
% Note: the function also adds three buttons at the bottom of each
% interactive windows: 'CANCEL', 'HELP' (if callback command
% is provided) and 'OK'.
%
% Example:
% res = inputgui('geometry', { 1 1 }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% res = inputgui('geom', { {2 1 [0 0] [1 1]} {2 1 [1 0] [1 1]} }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 1 Feb 2002
%
% See also: supergui(), eeglab()
% Copyright (C) Arnaud Delorme, CNL/Salk Institute, 27 Jan 2002, [email protected]
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result, userdat, strhalt, resstruct, instruct,strhalt_adv,resstruct_adv] = inputgui_mod_for_beapp( varargin);
if nargin < 2
help inputgui;
return;
end;
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'geometry' 'uilist' 'helpcom' 'title' 'userdata' 'mode' 'geomvert' };
options = { options{1:length(varargin)}; varargin{:} };
options = options(:)';
end;
% checking inputs
% ---------------
g = finputcheck(options, { 'geom' 'cell' [] {}; ...
'geometry' {'cell','integer'} [] []; ...
'uilist' 'cell' [] {}; ...
'helpcom' { 'string','cell' } { [] [] } ''; ...
'title' 'string' [] ''; ...
'eval' 'string' [] ''; ...
'helpbut' 'string' [] 'Help'; ...
'skipline' 'string' { 'on' 'off' } 'on'; ...
'addbuttons' 'string' { 'on' 'off' } 'on'; ...
'userdata' '' [] []; ...
'getresult' 'real' [] []; ...
'minwidth' 'real' [] 200; ...
'screenpos' '' [] []; ...
'mode' '' [] 'normal'; ...
'horizontalalignment' 'string' { 'left','right','center' } 'left';...
'geomvert' 'real' [] []; ... % start beapp additions
'buttoncolor' 'real' [] [0.6000 0.8000 1.0000];...
'backcolor' 'real' [] [0.8590, 1.0000, 1.0000];...
'nextbutton' 'string' {'on','off'} 'off';...
'backbutton' 'string' {'on','off'} 'off';...
'nextbuttoncall' 'string' [] '';...
'backbuttoncall' 'string' [] '';...
'tag' 'string' [] 'subsection_template_fig';...
'mutetagwarn' 'real' [0, 1] 0;...
'popoutpanel' 'real' [0, 1] 0;...
'adv_geometry' {'cell','integer'} [] []; ...
'adv_uilist' 'cell' [] {}; ...
'adv_geomvert' 'real' [] []; ... % start beapp additions
'grp_proc_info_in' '' [] [];...
}, 'inputgui');
if isstr(g), error(g); end;
if isempty(g.getresult)
if isstr(g.mode)
fig = figure('visible', 'off');
set(fig, 'name', g.title);
set(fig, 'userdata', g.userdata);
if ~g.mutetagwarn % if not part of a current panel progression
% beapp add start
if ~isempty(findobj('tag',g.tag'))
if g.popoutpanel == 1
answer = questdlg('You have another settings panel for this module open. Would you like to close that panel and open the selected settings?',...
'Multiple Module Settings Open','Go Back','Yes,close the other settings and continue','Go Back');
else
answer = questdlg('You have settings for another module open. Would you like to close those and open the selected settings?',...
'Multiple Module Settings Open','Go Back','Yes,close the other settings and continue','Go Back');
end
switch answer
case 'Go Back'
result = [];
userdat =[];
strhalt = '';
resstruct = [];
instruct =[];
% move open window to center
movegui(findobj('tag',g.tag'),'center');
uistack(findobj('tag',g.tag'),'top');
return;
case 'Yes,close the other settings and continue'
close(findobj('tag',g.tag));
end
end
end
set(fig, 'tag',g.tag);
% beapp add end
if ~iscell( g.geometry )
oldgeom = g.geometry;
g.geometry = {};
for row = 1:length(oldgeom)
g.geometry = { g.geometry{:} ones(1, oldgeom(row)) };
end;
end
% skip a line
if strcmpi(g.skipline, 'on'),
g.geometry = { g.geometry{:} [1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} {1 g.geom{1}{2} [0 g.geom{1}{2}-2] [1 1] } };
end;
g.uilist = { g.uilist{:}, {} };
end;
% beapp add -- add next and back buttons to geometry counts
if strcmpi(g.nextbutton, 'on') || strcmpi(g.backbutton, 'on'),
% add a row with 4 slots
g.geometry = { g.geometry{:} [1 1 1 1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} ...
{4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } };
end;
% fill in empty space for first 2 slots
g.uilist = { g.uilist{:}, {} {} };
if strcmpi(g.backbutton, 'on'),
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Back', 'tag' 'back' 'callback',...
'set(findobj(''parent'', gcf, ''tag'', ''ok''), ''userdata'', ''retuninginputui_back'');' } };
else
g.uilist = { g.uilist{:}, {'width' 80 'style','text','string','', 'tag', 'back'} };
end
if strcmpi(g.nextbutton, 'on'),
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'next', 'string', 'Next',...
'callback', 'set(findobj(''parent'', gcf, ''tag'', ''ok''), ''userdata'', ''retuninginputui_next'');' } };
else
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'text', 'tag', 'next', 'string', ''} };
end
end;
% add buttons
if strcmpi(g.addbuttons, 'on'),
g.geometry = { g.geometry{:} [1 1 1 1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} ...
{4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } };
end;
if ~isempty(g.helpcom)
if ~iscell(g.helpcom)
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', g.helpbut, 'tag', 'help', 'callback', g.helpcom } {} };
else
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'Help gui', 'callback', g.helpcom{1} } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'More help', 'callback', g.helpcom{2} } };
end;
else
g.uilist = { g.uilist{:}, {} {} };
end;
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'Save', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } };
end;
% add the three buttons (CANCEL HELP OK) at the bottom of the GUI
% ---------------------------------------------------------------
if ~isempty(g.geom)
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geom', g.geom, ...
'uilist', g.uilist, 'screenpos', g.screenpos,'backcolor',g.backcolor,'buttoncolor',g.buttoncolor,'horizontalalignment',g.horizontalalignment );
elseif isempty(g.geomvert)
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, ...
'uilist', g.uilist, 'screenpos', g.screenpos,'backcolor',g.backcolor,'buttoncolor',g.buttoncolor,'horizontalalignment',g.horizontalalignment );
else
if strcmpi(g.skipline, 'on'), g.geomvert = [g.geomvert(:)' 1]; end;
if strcmpi(g.addbuttons, 'on'),g.geomvert = [g.geomvert(:)' 1]; end;
if strcmpi(g.nextbutton, 'on')||strcmpi(g.backbutton, 'on'),g.geomvert = [g.geomvert(:)' 1]; end;
[tmp tmp2 allobj] = supergui_mod_for_beapp( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, ...
'uilist', g.uilist, 'screenpos', g.screenpos, 'geomvert', g.geomvert(:)','backcolor',g.backcolor,'buttoncolor',g.buttoncolor, 'horizontalalignment',g.horizontalalignment );
end;
else
fig = g.mode;
set(findobj('parent', fig, 'tag', 'ok'), 'userdata', []);
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
% evaluate command before waiting?
% --------------------------------
if ~isempty(g.eval), eval(g.eval); end;
instruct = outstruct(allobj); % Getting default values in the GUI.
% create figure and wait for return
% ---------------------------------
if isstr(g.mode) & (strcmpi(g.mode, 'plot') | strcmpi(g.mode, 'return') )
if strcmpi(g.mode, 'plot')
return; % only plot and returns
end;
else
strhalt_adv = '';
resstruct_adv = [];
% move_on = false;
% while ~move_on
waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata');
strhalt= get(findobj('parent', fig, 'tag', 'ok'), 'userdata');
% make and store settings from adv panel
if isequal(strhalt,'adv_settings_panel')
[~, ~, strhalt_adv, resstruct_adv, ~] = adv_inputgui_mod_for_beapp('geometry',g.adv_geometry,...
'uilist',g.adv_uilist,'geomvert',g.adv_geomvert,'tag',['adv_' g.tag]);
set(findobj('parent', fig, 'tag', 'ok'), 'userdata','refreshinputui');
% else
% move_on =1;
end
%end
end;
else
fig = g.getresult;
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
result = {};
userdat = [];
strhalt = '';
resstruct = [];
if ~(ishandle(fig)), return; end % Check if figure still exist
% output parameters
% -----------------
strhalt= get(findobj('parent', fig, 'tag', 'ok'), 'userdata');
[resstruct,result] = outstruct(allobj); % Output parameters
userdat = get(fig, 'userdata');
% if nargout >= 4
% resstruct = myguihandles(fig, g);
% end;
if isempty(g.getresult) && isstr(g.mode) && ( strcmp(g.mode, 'normal') || strcmp(g.mode, 'return') )
% if (~strcmp(strhalt, 'retuninginputui_back') && ~strcmp(strhalt, 'retuninginputui_next'))
close(fig);
% end
end;
drawnow; % for windows
% function for gui res (deprecated)
% --------------------
% function g = myguihandles(fig, g)
% h = findobj('parent', fig);
% if ~isempty(get(h(index), 'tag'))
% try,
% switch get(h(index), 'style')
% case 'edit', g = setfield(g, get(h(index), 'tag'), get(h(index), 'string'));
% case { 'value' 'radio' 'checkbox' 'listbox' 'popupmenu' 'radiobutton' }, ...
% g = setfield(g, get(h(index), 'tag'), get(h(index), 'value'));
% end;
% catch, end;
% end;
function [resstructout, resultout] = outstruct(allobj)
counter = 1;
resultout = {};
resstructout = [];
for index=1:length(allobj)
if isnumeric(allobj), currentobj = allobj(index);
else currentobj = allobj{index};
end;
if isnumeric(currentobj) | ~isprop(currentobj,'GetPropertySpecification') % To allow new object handles
try,
objstyle = get(currentobj, 'style');
switch lower( objstyle )
case { 'listbox', 'checkbox', 'radiobutton' 'popupmenu' 'radio' }
resultout{counter} = get( currentobj, 'value');
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
case 'edit'
resultout{counter} = get( currentobj, 'string');
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
end;
catch,
try
switch lower(get(currentobj,'type'))
case 'uitable'
tmp_uitable_holder.data = get(currentobj, 'data');
tmp_uitable_holder.header = get(currentobj, 'ColumnName'); % allows for duplicate names
resultout{counter} = tmp_uitable_holder;
if ~isempty(get(currentobj, 'tag')), resstructout = setfield(resstructout, get(currentobj, 'tag'), resultout{counter}); end;
counter = counter+1;
% will add in panels and tabs at some point
end
catch
end
end;
else
ps = currentobj.GetPropertySpecification;
resultout{counter} = arg_tovals(ps,false);
count = 1;
while isfield(resstructout, ['propgrid' int2str(count)])
count = count + 1;
end;
resstructout = setfield(resstructout, ['propgrid' int2str(count)], arg_tovals(ps,false));
end;
end;
|
github
|
lcnbeapp/beapp-master
|
WriteMatrix2Text.m
|
.m
|
beapp-master/Packages/CSDtoolbox/func/WriteMatrix2Text.m
| 1,415 |
utf_8
|
40fcf238991341aab27833a32ab9aeb5
|
% function WriteMatrix2Text ( X, FileName, FmtStg, CaseCol )
%
% This is a generic routine to write a data matrix to an ASCII file.
%
% Usage: WriteMatrix2Text ( X, FileName, FmtStg, CaseCol );
%
% Input arguments: X data matrix
% FileName file name string
% FmtStg formating string (default = '%9.3f')
% CaseCol numeric value indicating column offset
% requesting to also list case numbers
% (default = 0 to suppress case numbers)
%
% Updated: $Date: 2009/05/15 15:55:00 $ $Author: jk $
%
function WriteMatrix2File ( X, FileName, FmtStg, CaseCol )
if nargin < 2
help WriteMatrix2Text
disp('*** Error: Specify at least <X> and <FileName> as input');
return
end
if nargin < 3
FmtStg = '%9.3f';
end;
if nargin < 4
CaseCol = 0;
end;
disp(sprintf('Creating formatted (%s) matrix text file: %s',FmtStg,FileName));
if CaseCol > 0
disp(sprintf('Adding case numbers (%d chars)',CaseCol));
end;
fid = fopen(FileName,'w'); % open output file for write
for n = 1:size(X,1);
if CaseCol > 0
fprintf(fid, strcat('%',int2str(CaseCol),'d'), n); % print case#
end
fprintf(fid, FmtStg, X(n,:) ); % print all columns
fprintf(fid, char([13 10]) ); % print carriage return
end;
fclose(fid); % close output file
|
github
|
lcnbeapp/beapp-master
|
eeglab.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/eeglab.m
| 113,212 |
utf_8
|
883a8870e64e48ad66cf02195294076c
|
% eeglab() - Matlab graphic user interface environment for
% electrophysiological data analysis incorporating the ICA/EEG toolbox
% (Makeig et al.) developed at CNL / The Salk Institute, 1997-2001.
% Released 11/2002- as EEGLAB (Delorme, Makeig, et al.) at the Swartz Center
% for Computational Neuroscience, Institute for Neural Computation,
% University of California San Diego (http://sccn.ucsd.edu/).
% User feedback welcome: email [email protected]
%
% Authors: Arnaud Delorme and Scott Makeig, with substantial contributions
% from Colin Humphries, Sigurd Enghoff, Tzyy-Ping Jung, plus
% contributions
% from Tony Bell, Te-Won Lee, Luca Finelli and many other contributors.
%
% Description:
% EEGLAB is Matlab-based software for processing continuous or event-related
% EEG or other physiological data. It is designed for use by both novice and
% expert Matlab users. In normal use, the EEGLAB graphic interface calls
% graphic functions via pop-up function windows. The EEGLAB history mechanism
% can save the resulting Matlab calls to disk for later incorporation into
% Matlab scripts. A single data structure ('EEG') containing all dataset
% parameters may be accessed and modified directly from the Matlab commandline.
% EEGLAB now recognizes "plugins," sets of EEGLAB functions linked to the EEGLAB
% main menu through an "eegplugin_[name].m" function (Ex. >> help eeplugin_besa.m).
%
% Usage: 1) To (re)start EEGLAB, type
% >> eeglab % Ignores any loaded datasets
% 2) To redaw and update the EEGLAB interface, type
% >> eeglab redraw % Scans for non-empty datasets
% >> eeglab rebuild % Closes and rebuilds the EEGLAB window
% >> eeglab versions % State EEGLAB version number
%
% >> type "license.txt" % the GNU public license
% >> web http://sccn.ucsd.edu/eeglab/tutorial/ % the EEGLAB tutorial
% >> help eeg_checkset % the EEG dataset structure
%
% GUI Functions calling eponymous processing and plotting functions:
% ------------------------------------------------------------------
% <a href="matlab:helpwin pop_eegfilt">pop_eegfilt</a> - bandpass filter data (eegfilt())
% <a href="matlab:helpwin pop_eegplot">pop_eegplot</a> - scrolling multichannel data viewer (eegplot())
% <a href="matlab:helpwin pop_eegthresh">pop_eegthresh</a> - simple thresholding method (eegthresh())
% <a href="matlab:helpwin pop_envtopo">pop_envtopo</a> - plot ERP data and component contributions (envtopo())
% <a href="matlab:helpwin pop_epoch">pop_epoch</a> - extract epochs from a continuous dataset (epoch())
% <a href="matlab:helpwin pop_erpimage">pop_erpimage</a> - plot single epochs as an image (erpimage())
% <a href="matlab:helpwin pop_jointprob">pop_jointprob</a> - reject epochs using joint probability (jointprob())
% <a href="matlab:helpwin pop_loaddat">pop_loaddat</a> - load Neuroscan .DAT info file (loaddat())
% <a href="matlab:helpwin pop_loadcnt">pop_loadcnt</a> - load Neuroscan .CNT data (lndcnt())
% <a href="matlab:helpwin pop_loadeeg">pop_loadeeg</a> - load Neuroscan .EEG data (loadeeg())
% <a href="matlab:helpwin pop_loadbva">pop_loadbva</a> - load Brain Vision Analyser matlab files
% <a href="matlab:helpwin pop_plotdata">pop_plotdata</a> - plot data epochs in rectangular array (plotdata())
% <a href="matlab:helpwin pop_readegi">pop_readegi</a> - load binary EGI data file (readegi())
% <a href="matlab:helpwin pop_rejkurt">pop_rejkurt</a> - compute data kurtosis (rejkurt())
% <a href="matlab:helpwin pop_rejtrend">pop_rejtrend</a> - reject EEG epochs showing linear trends (rejtrend())
% <a href="matlab:helpwin pop_resample">pop_resample</a> - change data sampling rate (resample())
% <a href="matlab:helpwin pop_rmbase">pop_rmbase</a> - remove epoch baseline (rmbase())
% <a href="matlab:helpwin pop_runica">pop_runica</a> - run infomax ICA decomposition (runica())
% <a href="matlab:helpwin pop_newtimef">pop_newtimef</a> - event-related time-frequency (newtimef())
% <a href="matlab:helpwin pop_timtopo">pop_timtopo</a> - plot ERP and scalp maps (timtopo())
% <a href="matlab:helpwin pop_topoplot">pop_topoplot</a> - plot scalp maps (topoplot())
% <a href="matlab:helpwin pop_snapread">pop_snapread</a> - read Snapmaster .SMA files (snapread())
% <a href="matlab:helpwin pop_newcrossf">pop_newcrossf</a> - event-related cross-coherence (newcrossf())
% <a href="matlab:helpwin pop_spectopo">pop_spectopo</a> - plot all channel spectra and scalp maps (spectopo())
% <a href="matlab:helpwin pop_plottopo">pop_plottopo</a> - plot a data epoch in a topographic array (plottopo())
% <a href="matlab:helpwin pop_readedf">pop_readedf</a> - read .EDF EEG data format (readedf())
% <a href="matlab:helpwin pop_headplot">pop_headplot</a> - plot a 3-D data scalp map (headplot())
% <a href="matlab:helpwin pop_reref">pop_reref</a> - re-reference data (reref())
% <a href="matlab:helpwin pop_signalstat">pop_signalstat</a> - plot signal or component statistic (signalstat())
%
% Other GUI functions:
% -------------------
% <a href="matlab:helpwin pop_chanevent">pop_chanevent</a> - import events stored in data channel(s)
% <a href="matlab:helpwin pop_comments">pop_comments</a> - edit dataset comment ('about') text
% <a href="matlab:helpwin pop_compareerps">pop_compareerps</a> - compare two dataset ERPs using plottopo()
% <a href="matlab:helpwin pop_prop">pop_prop</a> - plot channel or component properties (erpimage, spectra, map)
% <a href="matlab:helpwin pop_copyset">pop_copyset</a> - copy dataset
% <a href="matlab:helpwin pop_dispcomp">pop_dispcomp</a> - display component scalp maps with reject buttons
% <a href="matlab:helpwin pop_editeventfield">pop_editeventfield</a> - edit event fields
% <a href="matlab:helpwin pop_editeventvals">pop_editeventvals</a> - edit event values
% <a href="matlab:helpwin pop_editset">pop_editset</a> - edit dataset information
% <a href="matlab:helpwin pop_export">pop_export</a> - export data or ica activity to ASCII file
% <a href="matlab:helpwin pop_expica">pop_expica</a> - export ica weights or inverse matrix to ASCII file
% <a href="matlab:helpwin pop_icathresh">pop_icathresh</a> - choose rejection thresholds (in development)
% <a href="matlab:helpwin pop_importepoch">pop_importepoch</a> - import epoch info ASCII file
% <a href="matlab:helpwin pop_importevent">pop_importevent</a> - import event info ASCII file
% <a href="matlab:helpwin pop_importpres">pop_importpres</a> - import Presentation info file
% <a href="matlab:helpwin pop_importev2">pop_importev2</a> - import Neuroscan ev2 file
% <a href="matlab:helpwin pop_loadset">pop_loadset</a> - load dataset
% <a href="matlab:helpwin pop_mergeset">pop_mergeset</a> - merge two datasets
% <a href="matlab:helpwin pop_rejepoch">pop_rejepoch</a> - reject pre-identified epochs in a EEG dataset
% <a href="matlab:helpwin pop_rejspec">pop_rejspec</a> - reject based on spectrum (computes spectrum -% eegthresh)
% <a href="matlab:helpwin pop_saveh">pop_saveh</a> - save EEGLAB command history
% <a href="matlab:helpwin pop_saveset">pop_saveset</a> - save dataset
% <a href="matlab:helpwin pop_select">pop_select</a> - select data (epochs, time points, channels ...)
% <a href="matlab:helpwin pop_selectevent">pop_selectevent</a> - select events
% <a href="matlab:helpwin pop_subcomp">pop_subcomp</a> - subtract components from data
%
% Non-GUI functions use for handling the EEG structure:
% ----------------------------------------------------
% <a href="matlab:helpwin eeg_checkset">eeg_checkset</a> - check dataset parameter consistency
% <a href="matlab:helpwin eeg_context">eeg_context</a> - return info about events surrounding given events
% <a href="matlab:helpwin pop_delset">pop_delset</a> - delete dataset
% <a href="matlab:helpwin pop_editoptions">pop_editoptions</a> - edit the option file
% <a href="matlab:helpwin eeg_emptyset">eeg_emptyset</a> - empty dataset
% <a href="matlab:helpwin eeg_epochformat">eeg_epochformat</a> - convert epoch array to structure
% <a href="matlab:helpwin eeg_eventformat">eeg_eventformat</a> - convert event array to structure
% <a href="matlab:helpwin eeg_getepochevent">eeg_getepochevent</a> - return event values for a subset of event types
% <a href="matlab:helpwin eeg_global">eeg_global</a> - global variables
% <a href="matlab:helpwin eeg_multieegplot">eeg_multieegplot</a> - plot several rejections (using different colors)
% <a href="matlab:helpwin eeg_options">eeg_options</a> - option file
% <a href="matlab:helpwin eeg_rejsuperpose">eeg_rejsuperpose</a> - use by rejmenu to superpose all rejections
% <a href="matlab:helpwin eeg_rejmacro">eeg_rejmacro</a> - used by all rejection functions
% <a href="matlab:helpwin pop_rejmenu">pop_rejmenu</a> - rejection menu (with all rejection methods visible)
% <a href="matlab:helpwin eeg_retrieve">eeg_retrieve</a> - retrieve dataset from ALLEEG
% <a href="matlab:helpwin eeg_store">eeg_store</a> - store dataset into ALLEEG
%
% Help functions:
% --------------
% <a href="matlab:helpwin eeg_helpadmin">eeg_helpadmin</a> - help on admin function
% <a href="matlab:helpwin eeg_helphelp">eeg_helphelp</a> - help on help
% <a href="matlab:helpwin eeg_helpmenu">eeg_helpmenu</a> - EEG help menus
% <a href="matlab:helpwin eeg_helppop">eeg_helppop</a> - help on pop_ and eeg_ functions
% <a href="matlab:helpwin eeg_helpsigproc">eeg_helpsigproc</a> - help on
% Copyright (C) 2001 Arnaud Delorme and Scott Makeig, Salk Institute,
% [email protected], [email protected].
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function varargout = eeglab( onearg )
ver = version;
if strcmpi(ver, '9.4.0.813654 (R2018a)')
disp('Link to install <a href="https://www.mathworks.com/downloads/web_downloads/download_update?release=R2018a&s_tid=ebrg_R2018a_2_1757132">2018a Update 2</a>');
errordlg( [ 'You are running Matlab version R2018a, which has important bugs' 10 'Matlab crashes when running EEGLAB in this vesion of Matlab' 10 'Install 2018a Update 2 to fix the issue (link on the command line)' ]);
end
if nargout > 0
varargout = { [] [] 0 {} [] };
%[ALLEEG, EEG, CURRENTSET, ALLCOM]
end;
% check Matlab version
% --------------------
vers = version;
tmpv = which('version');
if ~isempty(findstr(lower(tmpv), 'biosig'))
[tmpp tmp] = fileparts(tmpv);
rmpath(tmpp);
end;
% remove freemat folder if it exist
tmpPath = fileparts(fileparts(which('sread')));
newPath = fullfile(tmpPath, 'maybe-missing', 'freemat3.5');
if exist(newPath) == 7
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpath(newPath)
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
if str2num(vers(1)) < 7 && str2num(vers(1)) >= 5
tmpWarning = warning('backtrace');
warning backtrace off;
warning('You are using a Matlab version older than 7.0');
warning('This Matlab version is too old to run the current EEGLAB');
warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip');
warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3');
warning(tmpWarning);
return;
end;
% check Matlab version
% --------------------
vers = version;
indp = find(vers == '.');
if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end;
indp = find(vers == '.');
vers = str2num(vers(1:indp(2)-1));
if vers < 7.06
tmpWarning = warning('backtrace');
warning backtrace off;
warning('You are using a Matlab version older than 7.6 (2008a)');
warning('Some of the EEGLAB functions might not be functional');
warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip');
warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3');
warning(tmpWarning);
end;
% check for duplicate versions of EEGLAB
% --------------------------------------
eeglabpath = mywhich('eeglab.m');
eeglabpath = eeglabpath(1:end-length('eeglab.m'));
if nargin < 1
eeglabpath2 = '';
if strcmpi(eeglabpath, pwd) || strcmpi(eeglabpath(1:end-1), pwd)
cd('functions');
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpath(eeglabpath);
warning('on', 'MATLAB:rmpath:DirNotFound');
eeglabpath2 = mywhich('eeglab.m');
cd('..');
else
try, rmpath(eeglabpath); catch, end;
eeglabpath2 = mywhich('eeglab.m');
end;
if ~isempty(eeglabpath2)
%evalin('base', 'clear classes updater;'); % this clears all the variables
eeglabpath2 = eeglabpath2(1:end-length('eeglab.m'));
tmpWarning = warning('backtrace');
warning backtrace off;
disp('******************************************************');
warning('There are at least two versions of EEGLAB in your path');
warning(sprintf('One is at %s', eeglabpath));
warning(sprintf('The other one is at %s', eeglabpath2));
warning(tmpWarning);
end;
addpath(eeglabpath);
end;
% add the paths
% -------------
if strcmpi(eeglabpath, './') || strcmpi(eeglabpath, '.\'), eeglabpath = [ pwd filesep ]; end;
% solve BIOSIG problem
% --------------------
pathtmp = mywhich('wilcoxon_test');
if ~isempty(pathtmp)
try,
rmpath(pathtmp(1:end-15));
catch, end;
end;
% test for local SCCN copy
% ------------------------
if ~iseeglabdeployed2
addpathifnotinlist(eeglabpath);
if exist( fullfile( eeglabpath, 'functions', 'adminfunc') ) ~= 7
warning('EEGLAB subfolders not found');
end;
end;
% determine file format
% ---------------------
fileformat = 'maclinux';
comp = computer;
try
if strcmpi(comp(1:3), 'GLN') | strcmpi(comp(1:3), 'MAC') | strcmpi(comp(1:3), 'SOL')
fileformat = 'maclinux';
elseif strcmpi(comp(1:5), 'pcwin')
fileformat = 'pcwin';
end;
end;
% add paths
% ---------
if ~iseeglabdeployed2
tmp = which('eeglab_data.set');
if ~isempty(which('eeglab_data.set')) && ~isempty(which('GSN-HydroCel-32.sfp'))
warning backtrace off;
warning(sprintf([ '\n\nPath Warning: It appears that you have added the path to all of the\n' ...
'subfolders to EEGLAB. This may create issues with some EEGLAB extensions\n' ...
'If EEGLAB cannot start or your experience a large number of warning\n' ...
'messages, remove all the EEGLAB paths then go to the EEGLAB folder\n' ...
'and start EEGLAB which will add all the necessary paths.\n\n' ]));
warning backtrace on;
foldertorm = fileparts(which('fgetl.m'));
if ~isempty(strfind(foldertorm, 'eeglab'))
rmpath(foldertorm);
end;
foldertorm = fileparts(which('strjoin.m'));
if ~isempty(strfind(foldertorm, 'eeglab'))
rmpath(foldertorm);
end;
end;
myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]);
myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]);
myaddpath( eeglabpath, ['@mmo' filesep 'mmo.m'], 'functions');
myaddpath( eeglabpath, 'readeetraklocs.m', [ 'functions' filesep 'sigprocfunc' ]);
myaddpath( eeglabpath, 'supergui.m', [ 'functions' filesep 'guifunc' ]);
myaddpath( eeglabpath, 'pop_study.m', [ 'functions' filesep 'studyfunc' ]);
myaddpath( eeglabpath, 'pop_loadbci.m', [ 'functions' filesep 'popfunc' ]);
myaddpath( eeglabpath, 'statcond.m', [ 'functions' filesep 'statistics' ]);
myaddpath( eeglabpath, 'timefreq.m', [ 'functions' filesep 'timefreqfunc' ]);
myaddpath( eeglabpath, 'icademo.m', [ 'functions' filesep 'miscfunc' ]);
myaddpath( eeglabpath, 'eeglab1020.ced', [ 'functions' filesep 'resources' ]);
myaddpath( eeglabpath, 'startpane.m', [ 'functions' filesep 'javachatfunc' ]);
addpathifnotinlist(fullfile(eeglabpath, 'plugins'));
eeglab_options;
% remove path to to fmrlab if neceecessary
path_runica = fileparts(mywhich('runica'));
if length(path_runica) > 6 && strcmpi(path_runica(end-5:end), 'fmrlab')
rmpath(path_runica);
end;
% add path if toolboxes are missing
% ---------------------------------
signalpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'signal');
optimpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'optim');
if option_donotusetoolboxes
p1 = fileparts(mywhich('ttest'));
p2 = fileparts(mywhich('filtfilt'));
p3 = fileparts(mywhich('optimtool'));
p4 = fileparts(mywhich('gray2ind'));
if ~isempty(p1), rmpath(p1); end;
if ~isempty(p2), rmpath(p2); end;
if ~isempty(p3), rmpath(p3); end;
if ~isempty(p4), rmpath(p4); end;
end;
if ~license('test','signal_toolbox') || exist('pwelch') ~= 2
warning('off', 'MATLAB:dispatcher:nameConflict');
addpath( signalpath );
else
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpathifpresent( signalpath );
rmpathifpresent(optimpath);
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
if ~license('test','optim_toolbox') && ~ismatlab
addpath( optimpath );
else
warning('off', 'MATLAB:rmpath:DirNotFound');
rmpathifpresent( optimpath );
warning('on', 'MATLAB:rmpath:DirNotFound');
end;
% remove BIOSIG path which are not needed and might cause conflicts
biosigp{1} = fileparts(which('sopen.m'));
biosigp{2} = fileparts(which('regress_eog.m'));
biosigp{3} = fileparts(which('DecimalFactors.txt'));
removepath(fileparts(fileparts(biosigp{1})), biosigp{:})
else
eeglab_options;
end;
if nargin == 1 && strcmp(onearg, 'redraw')
if evalin('base', 'exist(''EEG'')', '0') == 1
evalin('base', 'eeg_global;');
end;
end;
eeg_global;
% remove empty datasets in ALLEEG
while ~isempty(ALLEEG) && isempty(ALLEEG(end).data)
ALLEEG(end) = [];
end;
if ~isempty(ALLEEG) && max(CURRENTSET) > length(ALLEEG)
CURRENTSET = 1;
EEG = eeg_retrieve(ALLEEG, CURRENTSET);
end;
% for the history function
% ------------------------
comtmp = 'warning off MATLAB:mir_warning_variable_used_as_function';
evalin('base' , comtmp, '');
evalin('caller', comtmp, '');
evalin('base', 'eeg_global;');
if nargin < 1 | exist('EEG') ~= 1
clear global EEG ALLEEG CURRENTSET ALLCOM LASTCOM STUDY;
CURRENTSTUDY = 0;
eeg_global;
EEG = eeg_emptyset;
eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;');
if ismatlab && get(0, 'screendepth') <= 8
disp('Warning: screen color depth too low, some colors will be inaccurate in time-frequency plots');
end;
end;
if nargin == 1
if strcmp(onearg, 'versions')
disp( [ 'EEGLAB v' eeg_getversion ] );
elseif strcmp(onearg, 'nogui')
if nargout < 1, clear ALLEEG; end; % do not return output var
return;
elseif strcmp(onearg, 'redraw')
if ~ismatlab,return; end;
W_MAIN = findobj('tag', 'EEGLAB');
if ~isempty(W_MAIN)
updatemenu;
if nargout < 1, clear ALLEEG; end; % do not return output var
return;
else
eegh('eeglab(''redraw'');');
end;
elseif strcmp(onearg, 'rebuild')
if ~ismatlab,return; end;
W_MAIN = findobj('tag', 'EEGLAB');
close(W_MAIN);
eeglab;
return;
else
fprintf(2,['EEGLAB Warning: Invalid argument ''' onearg '''. Restarting EEGLAB interface instead.\n']);
eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab(''rebuild'');');
end;
else
onearg = 'rebuild';
end;
ALLCOM = ALLCOM;
try, eval('colordef white;'); catch end;
% default option folder
% ---------------------
if ~iseeglabdeployed2
eeglab_options;
fprintf('eeglab: options file is %s%seeg_options.m\n', homefolder, filesep);
end;
% checking strings
% ----------------
e_try = 'try,';
e_catch = 'catch, eeglab_error; LASTCOM= ''''; clear EEGTMP ALLEEGTMP STUDYTMP; end;';
nocheck = e_try;
ret = 'if ~isempty(LASTCOM), if LASTCOM(1) == -1, LASTCOM = ''''; return; end; end;';
check = ['[EEG LASTCOM] = eeg_checkset(EEG, ''data'');' ret ' eegh(LASTCOM);' e_try];
checkcont = ['[EEG LASTCOM] = eeg_checkset(EEG, ''contdata'');' ret ' eegh(LASTCOM);' e_try];
checkica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'');' ret ' eegh(LASTCOM);' e_try];
checkepoch = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'');' ret ' eegh(LASTCOM);' e_try];
checkevent = ['[EEG LASTCOM] = eeg_checkset(EEG, ''event'');' ret ' eegh(LASTCOM);' e_try];
checkbesa = ['[EEG LASTCOM] = eeg_checkset(EEG, ''besa'');' ret ' eegh(''% no history yet for BESA dipole localization'');' e_try];
checkepochica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'');' ret ' eegh(LASTCOM);' e_try];
checkplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkepochplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
checkepochicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try];
% check string and backup old dataset
% -----------------------------------
backup = [ 'if CURRENTSET ~= 0,' ...
' [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, CURRENTSET, ''savegui'');' ...
' eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET, ''''savedata'''');'');' ...
'end;' ];
storecall = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);'');';
storenewcall = '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM);';
storeallcall = [ 'if ~isempty(ALLEEG) & ~isempty(ALLEEG(1).data), ALLEEG = eeg_checkset(ALLEEG);' ...
'EEG = eeg_retrieve(ALLEEG, CURRENTSET); eegh(''ALLEEG = eeg_checkset(ALLEEG); EEG = eeg_retrieve(ALLEEG, CURRENTSET);''); end;' ];
testeegtmp = 'if exist(''EEGTMP'') == 1, EEG = EEGTMP; clear EEGTMP; end;'; % for backward compatibility
ifeeg = 'if ~isempty(LASTCOM) & ~isempty(EEG),';
ifeegnh = 'if ~isempty(LASTCOM) & ~isempty(EEG) & ~isempty(findstr(''='',LASTCOM)),';
% nh = no dataset history
% -----------------------
e_storeall_nh = [e_catch 'eegh(LASTCOM);' ifeeg storeallcall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_hist_nh = [e_catch 'eegh(LASTCOM);'];
% same as above but also save history in dataset
% ----------------------------------------------
e_newset = [e_catch 'EEG = eegh(LASTCOM, EEG);' testeegtmp ifeeg storenewcall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_store = [e_catch 'EEG = eegh(LASTCOM, EEG);' ifeegnh storecall 'disp(''Done.''); end; eeglab(''redraw'');'];
e_hist = [e_catch 'EEG = eegh(LASTCOM, EEG);'];
e_histdone = [e_catch 'EEG = eegh(LASTCOM, EEG); if ~isempty(LASTCOM), disp(''Done.''); end;' ];
% study checking
% --------------
e_load_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); ALLEEG = ALLEEGTMP; EEG = ALLEEG; CURRENTSET = [1:length(EEG)]; eegh(''CURRENTSTUDY = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];''); CURRENTSTUDY = 1; disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');'];
e_plot_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; % ALLEEG not modified
% build structures for plugins
% ----------------------------
trystrs.no_check = e_try;
trystrs.check_data = check;
trystrs.check_ica = checkica;
trystrs.check_cont = checkcont;
trystrs.check_epoch = checkepoch;
trystrs.check_event = checkevent;
trystrs.check_epoch_ica = checkepochica;
trystrs.check_chanlocs = checkplot;
trystrs.check_epoch_chanlocs = checkepochplot;
trystrs.check_epoch_ica_chanlocs = checkepochicaplot;
catchstrs.add_to_hist = e_hist;
catchstrs.store_and_hist = e_store;
catchstrs.new_and_hist = e_newset;
catchstrs.new_non_empty = e_newset;
catchstrs.update_study = e_plot_study;
% create eeglab figure
% --------------------
javaobj = eeg_mainfig(onearg);
% detecting icalab
% ----------------
if exist('icalab')
disp('ICALAB toolbox detected (algo. added to "run ICA" interface)');
end;
if ~iseeglabdeployed2
% check for older version of Fieldtrip and presence of topoplot
% -------------------------------------------------------------
if ismatlab
ptopoplot = fileparts(mywhich('cbar'));
ptopoplot2 = fileparts(mywhich('topoplot'));
if ~strcmpi(ptopoplot, ptopoplot2),
%disp(' Warning: duplicate function topoplot.m in Fieldtrip and EEGLAB');
%disp(' EEGLAB function will prevail and call the Fieldtrip one when appropriate');
addpath(ptopoplot);
end;
end;
end;
cb_importdata = [ nocheck '[EEG LASTCOM] = pop_importdata;' e_newset ];
cb_readegi = [ nocheck '[EEG LASTCOM] = pop_readegi;' e_newset ];
cb_readsegegi = [ nocheck '[EEG LASTCOM] = pop_readsegegi;' e_newset ];
cb_readegiepo = [ nocheck '[EEG LASTCOM] = pop_importegimat;' e_newset ];
cb_loadbci = [ nocheck '[EEG LASTCOM] = pop_loadbci;' e_newset ];
cb_snapread = [ nocheck '[EEG LASTCOM] = pop_snapread;' e_newset ];
cb_loadcnt = [ nocheck '[EEG LASTCOM] = pop_loadcnt;' e_newset ];
cb_loadeeg = [ nocheck '[EEG LASTCOM] = pop_loadeeg;' e_newset ];
cb_biosig = [ nocheck '[EEG LASTCOM] = pop_biosig; ' e_newset ];
cb_fileio = [ nocheck '[EEG LASTCOM] = pop_fileio; ' e_newset ];
cb_fileio2 = [ nocheck '[EEG LASTCOM] = pop_fileiodir;' e_newset ];
cb_importepoch = [ checkepoch '[EEG LASTCOM] = pop_importepoch(EEG);' e_store ];
cb_loaddat = [ checkepoch '[EEG LASTCOM]= pop_loaddat(EEG);' e_store ];
cb_importevent = [ check '[EEG LASTCOM] = pop_importevent(EEG);' e_store ];
cb_chanevent = [ check '[EEG LASTCOM]= pop_chanevent(EEG);' e_store ];
cb_importpres = [ check '[EEG LASTCOM]= pop_importpres(EEG);' e_store ];
cb_importev2 = [ check '[EEG LASTCOM]= pop_importev2(EEG);' e_store ];
cb_importerplab= [ check '[EEG LASTCOM]= pop_importerplab(EEG);' e_store ];
cb_export = [ check 'LASTCOM = pop_export(EEG);' e_histdone ];
cb_expica1 = [ check 'LASTCOM = pop_expica(EEG, ''weights'');' e_histdone ];
cb_expica2 = [ check 'LASTCOM = pop_expica(EEG, ''inv'');' e_histdone ];
cb_expevents = [ check 'LASTCOM = pop_expevents(EEG);' e_histdone ];
cb_expdata = [ check 'LASTCOM = pop_writeeeg(EEG);' e_histdone ];
cb_loadset = [ nocheck '[EEG LASTCOM] = pop_loadset;' e_newset];
cb_saveset = [ check '[EEG LASTCOM] = pop_saveset(EEG, ''savemode'', ''resave'');' e_store ];
cb_savesetas = [ check '[EEG LASTCOM] = pop_saveset(EEG);' e_store ];
cb_delset = [ nocheck '[ALLEEG LASTCOM] = pop_delset(ALLEEG, -CURRENTSET);' e_hist_nh 'eeglab redraw;' ];
cb_study1 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], ALLEEG , ''gui'', ''on'');' e_load_study];
cb_study2 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], isempty(ALLEEG), ''gui'', ''on'');' e_load_study];
cb_studyerp = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_studyerp;' e_load_study];
cb_loadstudy = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_loadstudy; if ~isempty(LASTCOM), STUDYTMP = std_renamestudyfiles(STUDYTMP, ALLEEGTMP); end;' e_load_study];
cb_savestudy1 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG, ''savemode'', ''resave'');' e_load_study];
cb_savestudy2 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG);' e_load_study];
cb_clearstudy = 'LASTCOM = ''STUDY = []; CURRENTSTUDY = 0; ALLEEG = []; EEG=[]; CURRENTSET=[];''; eval(LASTCOM); eegh( LASTCOM ); eeglab redraw;';
cb_editoptions = [ nocheck 'if isfield(ALLEEG, ''nbchan''), LASTCOM = pop_editoptions(length([ ALLEEG.nbchan ]) >1);' ...
'else LASTCOM = pop_editoptions(0); end;' e_storeall_nh];
cb_plugin1 = [ nocheck 'if plugin_extract(''import'', PLUGINLIST) , close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ];
cb_plugin2 = [ nocheck 'if plugin_extract(''process'', PLUGINLIST), close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ];
cb_saveh1 = [ nocheck 'LASTCOM = pop_saveh(EEG.history);' e_hist_nh];
cb_saveh2 = [ nocheck 'LASTCOM = pop_saveh(ALLCOM);' e_hist_nh];
cb_runsc = [ nocheck 'LASTCOM = pop_runscript;' e_hist ];
cb_quit = [ 'close(gcf); disp(''To save the EEGLAB command history >> pop_saveh(ALLCOM);'');' ...
'clear global EEG ALLEEG LASTCOM CURRENTSET;'];
cb_editset = [ check '[EEG LASTCOM] = pop_editset(EEG);' e_store];
cb_editeventf = [ checkevent '[EEG LASTCOM] = pop_editeventfield(EEG);' e_store];
cb_editeventv = [ checkevent '[EEG LASTCOM] = pop_editeventvals(EEG);' e_store];
cb_comments = [ check '[EEG.comments LASTCOM] =pop_comments(EEG.comments, ''About this dataset'');' e_store];
cb_chanedit = [ 'disp(''IMPORTANT: After importing/modifying data channels, you must close'');' ...
'disp(''the channel editing window for the changes to take effect in EEGLAB.'');' ...
'disp(''TIP: Call this function directy from the prompt, ">> pop_chanedit([]);"'');' ...
'disp('' to convert between channel location file formats'');' ...
'[EEG TMPINFO TMP LASTCOM] = pop_chanedit(EEG); if ~isempty(LASTCOM), EEG = eeg_checkset(EEG, ''chanlocsize'');' ...
'clear TMPINFO TMP; EEG = eegh(LASTCOM, EEG);' storecall 'end; eeglab(''redraw'');'];
cb_select = [ check '[EEG LASTCOM] = pop_select(EEG);' e_newset];
cb_rmdat = [ checkevent '[EEG LASTCOM] = pop_rmdat(EEG);' e_newset];
cb_selectevent = [ checkevent '[EEG TMP LASTCOM] = pop_selectevent(EEG); clear TMP;' e_newset ];
cb_copyset = [ check '[ALLEEG EEG CURRENTSET LASTCOM] = pop_copyset(ALLEEG, CURRENTSET); eeglab(''redraw'');' e_hist_nh];
cb_mergeset = [ check '[EEG LASTCOM] = pop_mergeset(ALLEEG);' e_newset];
cb_resample = [ check '[EEG LASTCOM] = pop_resample(EEG);' e_newset];
cb_eegfilt = [ check '[EEG LASTCOM] = pop_eegfilt(EEG);' e_newset];
cb_interp = [ check '[EEG LASTCOM] = pop_interp(EEG); ' e_newset];
cb_reref = [ check '[EEG LASTCOM] = pop_reref(EEG);' e_newset];
cb_eegplot = [ checkcont '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist];
cb_epoch = [ check '[EEG tmp LASTCOM] = pop_epoch(EEG); clear tmp;' e_newset check '[EEG LASTCOM] = pop_rmbase(EEG);' e_newset];
cb_rmbase = [ check '[EEG LASTCOM] = pop_rmbase(EEG);' e_store];
cb_runica = [ check '[EEG LASTCOM] = pop_runica(EEG);' e_store];
cb_subcomp = [ checkica '[EEG LASTCOM] = pop_subcomp(EEG);' e_newset];
%cb_chanrej = [ check 'pop_rejchan(EEG); LASTCOM = '''';' e_hist];
cb_chanrej = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejchan(EEG); clear tmp1 tmp2;' e_hist];
cb_autorej = [ checkepoch '[EEG tmpp LASTCOM] = pop_autorej(EEG); clear tmpp;' e_hist];
cb_rejcont = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejcont(EEG); clear tmp1 tmp2;' e_hist];
cb_rejmenu1 = [ check 'pop_rejmenu(EEG, 1); LASTCOM = '''';' e_hist];
cb_eegplotrej1 = [ check '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist];
cb_eegthresh1 = [ checkepoch '[TMP LASTCOM] = pop_eegthresh(EEG, 1); clear TMP;' e_hist];
cb_rejtrend1 = [ checkepoch '[EEG LASTCOM] = pop_rejtrend(EEG, 1);' e_store];
cb_jointprob1 = [ checkepoch '[EEG LASTCOM] = pop_jointprob(EEG, 1);' e_store];
cb_rejkurt1 = [ checkepoch '[EEG LASTCOM] = pop_rejkurt(EEG, 1);' e_store];
cb_rejspec1 = [ checkepoch '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store];
cb_rejsup1 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); eegh(LASTCOM);' ...
'LASTCOM = ''EEG.reject.icarejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ];
cb_rejsup2 = [ checkepoch '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ...
'[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset];
cb_selectcomps = [ checkicaplot '[EEG LASTCOM] = pop_selectcomps(EEG);' e_store];
cb_rejmenu2 = [ checkepochica 'pop_rejmenu(EEG, 0); LASTCOM ='''';' e_hist];
cb_eegplotrej2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0);' e_hist];
cb_eegthresh2 = [ checkepochica '[TMP LASTCOM] = pop_eegthresh(EEG, 0); clear TMP;' e_hist];
cb_rejtrend2 = [ checkepochica '[EEG LASTCOM] = pop_rejtrend(EEG, 0);' e_store];
cb_jointprob2 = [ checkepochica '[EEG LASTCOM] = pop_jointprob(EEG, 0);' e_store];
cb_rejkurt2 = [ checkepochica '[EEG LASTCOM] = pop_rejkurt(EEG, 0);' e_store];
cb_rejspec2 = [ checkepochica '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store];
cb_rejsup3 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); eegh(LASTCOM);' ...
'LASTCOM = ''EEG.reject.rejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ];
cb_rejsup4 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ...
'[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset ];
cb_topoblank1 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ...
'''''electrodes'''', ''''labelpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist];
cb_topoblank2 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ...
'''''electrodes'''', ''''numpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist];
cb_eegplot1 = [ check 'LASTCOM = pop_eegplot(EEG, 1, 1, 1);' e_hist];
cb_spectopo1 = [ check 'LASTCOM = pop_spectopo(EEG, 1);' e_hist];
cb_prop1 = [ checkplot 'LASTCOM = pop_prop(EEG,1);' e_hist];
cb_erpimage1 = [ checkepoch 'LASTCOM = pop_erpimage(EEG, 1, eegh(''find'',''pop_erpimage(EEG,1''));' e_hist];
cb_timtopo = [ checkplot 'LASTCOM = pop_timtopo(EEG);' e_hist];
cb_plottopo = [ check 'LASTCOM = pop_plottopo(EEG);' e_hist];
cb_topoplot1 = [ checkplot 'LASTCOM = pop_topoplot(EEG, 1);' e_hist];
cb_headplot1 = [ checkplot '[EEG LASTCOM] = pop_headplot(EEG, 1);' e_store];
cb_comperp1 = [ checkepoch 'LASTCOM = pop_comperp(ALLEEG);' e_hist];
cb_eegplot2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0, 1, 1);' e_hist];
cb_spectopo2 = [ checkicaplot 'LASTCOM = pop_spectopo(EEG, 0);' e_hist];
cb_topoplot2 = [ checkicaplot 'LASTCOM = pop_topoplot(EEG, 0);' e_hist];
cb_headplot2 = [ checkicaplot '[EEG LASTCOM] = pop_headplot(EEG, 0);' e_store];
cb_prop2 = [ checkicaplot 'LASTCOM = pop_prop(EEG,0);' e_hist];
cb_erpimage2 = [ checkepochica 'LASTCOM = pop_erpimage(EEG, 0, eegh(''find'',''pop_erpimage(EEG,0''));' e_hist];
cb_envtopo1 = [ checkica 'LASTCOM = pop_envtopo(EEG);' e_hist];
cb_envtopo2 = [ checkica 'if length(ALLEEG) == 1, error(''Need at least 2 datasets''); end; LASTCOM = pop_envtopo(ALLEEG);' e_hist];
cb_plotdata2 = [ checkepochica '[tmpeeg LASTCOM] = pop_plotdata(EEG, 0); clear tmpeeg;' e_hist];
cb_comperp2 = [ checkepochica 'LASTCOM = pop_comperp(ALLEEG, 0);' e_hist];
cb_signalstat1 = [ check 'LASTCOM = pop_signalstat(EEG, 1);' e_hist];
cb_signalstat2 = [ checkica 'LASTCOM = pop_signalstat(EEG, 0);' e_hist];
cb_eventstat = [ checkevent 'LASTCOM = pop_eventstat(EEG);' e_hist];
cb_timef1 = [ check 'LASTCOM = pop_newtimef(EEG, 1, eegh(''find'',''pop_newtimef(EEG,1''));' e_hist];
cb_crossf1 = [ check 'LASTCOM = pop_newcrossf(EEG, 1,eegh(''find'',''pop_newcrossf(EEG,1''));' e_hist];
cb_timef2 = [ checkica 'LASTCOM = pop_newtimef(EEG, 0, eegh(''find'',''pop_newtimef(EEG,0''));' e_hist];
cb_crossf2 = [ checkica 'LASTCOM = pop_newcrossf(EEG, 0,eegh(''find'',''pop_newcrossf(EEG,0''));' e_hist];
cb_study3 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_study(STUDY, ALLEEG, ''gui'', ''on'');' e_load_study];
cb_studydesign = [ nocheck '[STUDYTMP LASTCOM] = pop_studydesign(STUDY, ALLEEG); ALLEEGTMP = ALLEEG;' e_plot_study];
cb_precomp = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG);' e_plot_study];
cb_chanplot = [ nocheck '[STUDYTMP LASTCOM] = pop_chanplot(STUDY, ALLEEG); ALLEEGTMP=ALLEEG;' e_plot_study];
cb_precomp2 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG, ''components'');' e_plot_study];
cb_preclust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_preclust(STUDY, ALLEEG);' e_plot_study];
cb_clust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_clust(STUDY, ALLEEG);' e_plot_study];
cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG);' e_plot_study];
%
% % add STUDY plugin menus
% if exist('eegplugin_stderpimage')
% structure.uilist = { { } ...
% {'style' 'pushbutton' 'string' 'Plot ERPimage' 'Callback' 'stderpimageplugin_plot(''onecomp'', gcf);' } { } ...
% {'style' 'pushbutton' 'string' 'Plot ERPimage(s)' 'Callback' 'stderpimageplugin_plot(''oneclust'', gcf);' } };
% structure.geometry = { [1] [1 0.3 1] };
% arg = vararg2str( { structure } );
% cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG, [], ' arg ');' e_load_study];
% end;
% menu definition
% ---------------
if ismatlab
% defaults
% --------
% startup:on
% study:off
% chanloc:off
% epoch:on
% continuous:on
on = 'study:on';
onnostudy = '';
ondata = 'startup:off';
onepoch = 'startup:off;continuous:off';
ondatastudy = 'startup:off;study:on';
onchannel = 'startup:off;chanloc:on';
onepochchan = 'startup:off;continuous:off;chanloc:on';
onstudy = 'startup:off;epoch:off;continuous:off;study:on';
W_MAIN = findobj('tag', 'EEGLAB');
EEGUSERDAT = get(W_MAIN, 'userdata');
set(W_MAIN, 'MenuBar', 'none');
file_m = uimenu( W_MAIN, 'Label', 'File' , 'userdata', on);
import_m = uimenu( file_m, 'Label', 'Import data' , 'userdata', onnostudy);
neuro_m = uimenu( import_m, 'Label', 'Using EEGLAB functions and plugins' , 'tag', 'import data' , 'userdata', onnostudy);
epoch_m = uimenu( file_m, 'Label', 'Import epoch info', 'tag', 'import epoch', 'userdata', onepoch);
event_m = uimenu( file_m, 'Label', 'Import event info', 'tag', 'import event', 'userdata', ondata);
exportm = uimenu( file_m, 'Label', 'Export' , 'tag', 'export' , 'userdata', ondata);
edit_m = uimenu( W_MAIN, 'Label', 'Edit' , 'userdata', ondata);
tools_m = uimenu( W_MAIN, 'Label', 'Tools', 'tag', 'tools' , 'userdata', ondatastudy);
plot_m = uimenu( W_MAIN, 'Label', 'Plot', 'tag', 'plot' , 'userdata', ondata);
loc_m = uimenu( plot_m, 'Label', 'Channel locations' , 'userdata', onchannel);
std_m = uimenu( W_MAIN, 'Label', 'Study', 'tag', 'study' , 'userdata', onstudy);
set_m = uimenu( W_MAIN, 'Label', 'Datasets' , 'userdata', ondatastudy);
help_m = uimenu( W_MAIN, 'Label', 'Help' , 'userdata', on);
uimenu( neuro_m, 'Label', 'From ASCII/float file or Matlab array' , 'CallBack', cb_importdata);
%uimenu( neuro_m, 'Label', 'From Netstation .mff (FILE-IO toolbox)', 'CallBack', cb_fileio2, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From Netstation binary simple file' , 'CallBack', cb_readegi, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From Multiple seg. Netstation files' , 'CallBack', cb_readsegegi);
uimenu( neuro_m, 'Label', 'From Netstation Matlab files' , 'CallBack', cb_readegiepo);
uimenu( neuro_m, 'Label', 'From BCI2000 ASCII file' , 'CallBack', cb_loadbci, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From Snapmaster .SMA file' , 'CallBack', cb_snapread, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From Neuroscan .CNT file' , 'CallBack', cb_loadcnt, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From Neuroscan .EEG file' , 'CallBack', cb_loadeeg);
% BIOSIG MENUS
% ------------
uimenu( neuro_m, 'Label', 'From Biosemi BDF file (BIOSIG toolbox)', 'CallBack' , cb_biosig, 'Separator', 'on');
uimenu( neuro_m, 'Label', 'From EDF/EDF+/GDF files (BIOSIG toolbox)', 'CallBack', cb_biosig);
uimenu( epoch_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importepoch);
uimenu( epoch_m, 'Label', 'From Neuroscan .DAT file' , 'CallBack', cb_loaddat);
uimenu( event_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importevent);
uimenu( event_m, 'Label', 'From data channel' , 'CallBack', cb_chanevent);
uimenu( event_m, 'Label', 'From Presentation .LOG file' , 'CallBack', cb_importpres);
uimenu( event_m, 'Label', 'From E-Prime ASCII (text) file' , 'CallBack', cb_importevent);
uimenu( event_m, 'Label', 'From Neuroscan .ev2 file' , 'CallBack', cb_importev2); ;
uimenu( event_m, 'Label', 'From ERPLAB text files' , 'CallBack', cb_importerplab);
uimenu( exportm, 'Label', 'Data and ICA activity to text file' , 'CallBack', cb_export);
uimenu( exportm, 'Label', 'Weight matrix to text file' , 'CallBack', cb_expica1);
uimenu( exportm, 'Label', 'Inverse weight matrix to text file' , 'CallBack', cb_expica2);
uimenu( exportm, 'Label', 'Events to text file' , 'CallBack', cb_expevents);
uimenu( exportm, 'Label', 'Data to EDF/BDF/GDF file' , 'CallBack', cb_expdata, 'separator', 'on');
uimenu( file_m, 'Label', 'Load existing dataset' , 'userdata', onnostudy, 'CallBack', cb_loadset, 'Separator', 'on');
uimenu( file_m, 'Label', 'Save current dataset(s)' , 'userdata', ondatastudy, 'CallBack', cb_saveset);
uimenu( file_m, 'Label', 'Save current dataset as' , 'userdata', ondata, 'CallBack', cb_savesetas);
uimenu( file_m, 'Label', 'Clear dataset(s)' , 'userdata', ondata, 'CallBack', cb_delset);
std2_m = uimenu( file_m, 'Label', 'Create study' , 'userdata', on , 'Separator', 'on');
uimenu( std2_m, 'Label', 'Using all loaded datasets' , 'userdata', ondata , 'Callback', cb_study1);
uimenu( std2_m, 'Label', 'Browse for datasets' , 'userdata', on , 'Callback', cb_study2);
uimenu( std2_m, 'Label', 'Simple ERP STUDY' , 'userdata', on , 'Callback', cb_studyerp);
uimenu( file_m, 'Label', 'Load existing study' , 'userdata', on , 'CallBack', cb_loadstudy,'Separator', 'on' );
uimenu( file_m, 'Label', 'Save current study' , 'userdata', onstudy, 'CallBack', cb_savestudy1);
uimenu( file_m, 'Label', 'Save current study as' , 'userdata', onstudy, 'CallBack', cb_savestudy2);
uimenu( file_m, 'Label', 'Clear study / Clear all' , 'userdata', ondatastudy, 'CallBack', cb_clearstudy);
uimenu( file_m, 'Label', 'Memory and other options' , 'userdata', on , 'CallBack', cb_editoptions, 'Separator', 'on');
hist_m = uimenu( file_m, 'Label', 'History scripts' , 'userdata', on , 'Separator', 'on');
uimenu( hist_m, 'Label', 'Save dataset history script' , 'userdata', ondata , 'CallBack', cb_saveh1);
uimenu( hist_m, 'Label', 'Save session history script' , 'userdata', ondatastudy, 'CallBack', cb_saveh2);
uimenu( hist_m, 'Label', 'Run script' , 'userdata', on , 'CallBack', cb_runsc);
plugin_m = uimenu( file_m, 'Label', 'Manage EEGLAB extensions' , 'userdata', on);
uimenu( plugin_m, 'Label', 'Data import extensions' , 'userdata', on , 'CallBack', cb_plugin1);
uimenu( plugin_m, 'Label', 'Data processing extensions' , 'userdata', on , 'CallBack', cb_plugin2);
uimenu( file_m, 'Label', 'Quit' , 'userdata', on , 'CallBack', cb_quit, 'Separator', 'on');
uimenu( edit_m, 'Label', 'Dataset info' , 'userdata', ondata, 'CallBack', cb_editset);
uimenu( edit_m, 'Label', 'Event fields' , 'userdata', ondata, 'CallBack', cb_editeventf);
uimenu( edit_m, 'Label', 'Event values' , 'userdata', ondata, 'CallBack', cb_editeventv);
uimenu( edit_m, 'Label', 'About this dataset' , 'userdata', ondata, 'CallBack', cb_comments);
uimenu( edit_m, 'Label', 'Channel locations' , 'userdata', ondata, 'CallBack', cb_chanedit);
uimenu( edit_m, 'Label', 'Select data' , 'userdata', ondata, 'CallBack', cb_select, 'Separator', 'on');
uimenu( edit_m, 'Label', 'Select data using events' , 'userdata', ondata, 'CallBack', cb_rmdat);
uimenu( edit_m, 'Label', 'Select epochs or events' , 'userdata', ondata, 'CallBack', cb_selectevent);
uimenu( edit_m, 'Label', 'Copy current dataset' , 'userdata', ondata, 'CallBack', cb_copyset, 'Separator', 'on');
uimenu( edit_m, 'Label', 'Append datasets' , 'userdata', ondata, 'CallBack', cb_mergeset);
uimenu( edit_m, 'Label', 'Delete dataset(s) from memory' , 'userdata', ondata, 'CallBack', cb_delset);
uimenu( tools_m, 'Label', 'Change sampling rate' , 'userdata', ondatastudy, 'CallBack', cb_resample);
filter_m = uimenu( tools_m, 'Label', 'Filter the data' , 'userdata', ondatastudy, 'tag', 'filter');
uimenu( filter_m, 'Label', 'Basic FIR filter (legacy)' , 'userdata', ondatastudy, 'CallBack', cb_eegfilt);
uimenu( tools_m, 'Label', 'Re-reference' , 'userdata', ondata, 'CallBack', cb_reref);
uimenu( tools_m, 'Label', 'Interpolate electrodes' , 'userdata', ondata, 'CallBack', cb_interp);
uimenu( tools_m, 'Label', 'Reject continuous data by eye' , 'userdata', ondata, 'CallBack', cb_eegplot);
uimenu( tools_m, 'Label', 'Extract epochs' , 'userdata', ondata, 'CallBack', cb_epoch, 'Separator', 'on');
uimenu( tools_m, 'Label', 'Remove baseline' , 'userdata', ondatastudy, 'CallBack', cb_rmbase);
uimenu( tools_m, 'Label', 'Run ICA' , 'userdata', ondatastudy, 'CallBack', cb_runica, 'foregroundcolor', 'b', 'Separator', 'on');
uimenu( tools_m, 'Label', 'Remove components' , 'userdata', ondata, 'CallBack', cb_subcomp);
uimenu( tools_m, 'Label', 'Automatic channel rejection' , 'userdata', ondata, 'CallBack', cb_chanrej, 'Separator', 'on');
uimenu( tools_m, 'Label', 'Automatic continuous rejection' , 'userdata', ondata, 'CallBack', cb_rejcont);
uimenu( tools_m, 'Label', 'Automatic epoch rejection' , 'userdata', onepoch, 'CallBack', cb_autorej);
rej_m1 = uimenu( tools_m, 'Label', 'Reject data epochs' , 'userdata', onepoch);
rej_m2 = uimenu( tools_m, 'Label', 'Reject data using ICA' , 'userdata', ondata );
uimenu( rej_m1, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu1);
uimenu( rej_m1, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej1);
uimenu( rej_m1, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh1);
uimenu( rej_m1, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend1);
uimenu( rej_m1, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob1);
uimenu( rej_m1, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt1);
uimenu( rej_m1, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec1);
uimenu( rej_m1, 'Label', 'Export marks to ICA reject' , 'userdata', onepoch, 'CallBack', cb_rejsup1, 'separator', 'on');
uimenu( rej_m1, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup2, 'separator', 'on', 'foregroundcolor', 'b');
uimenu( rej_m2, 'Label', 'Reject components by map' , 'userdata', ondata , 'CallBack', cb_selectcomps);
uimenu( rej_m2, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu2, 'Separator', 'on');
uimenu( rej_m2, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej2);
uimenu( rej_m2, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh2);
uimenu( rej_m2, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend2);
uimenu( rej_m2, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob2);
uimenu( rej_m2, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt2);
uimenu( rej_m2, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec2);
uimenu( rej_m2, 'Label', 'Export marks to data reject' , 'userdata', onepoch, 'CallBack', cb_rejsup3, 'separator', 'on');
uimenu( rej_m2, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup4, 'separator', 'on', 'foregroundcolor', 'b');
uimenu( loc_m, 'Label', 'By name' , 'userdata', onchannel, 'CallBack', cb_topoblank1);
uimenu( loc_m, 'Label', 'By number' , 'userdata', onchannel, 'CallBack', cb_topoblank2);
uimenu( plot_m, 'Label', 'Channel data (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot1, 'Separator', 'on');
uimenu( plot_m, 'Label', 'Channel spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo1);
uimenu( plot_m, 'Label', 'Channel properties' , 'userdata', ondata , 'CallBack', cb_prop1);
uimenu( plot_m, 'Label', 'Channel ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage1);
ERP_m = uimenu( plot_m, 'Label', 'Channel ERPs' , 'userdata', onepoch);
uimenu( ERP_m, 'Label', 'With scalp maps' , 'CallBack', cb_timtopo);
uimenu( ERP_m, 'Label', 'In scalp/rect. array' , 'CallBack', cb_plottopo);
topo_m = uimenu( plot_m, 'Label', 'ERP map series' , 'userdata', onepochchan);
uimenu( topo_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot1);
uimenu( topo_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot1);
uimenu( plot_m, 'Label', 'Sum/Compare ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp1);
uimenu( plot_m, 'Label', 'Component activations (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot2,'Separator', 'on');
uimenu( plot_m, 'Label', 'Component spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo2);
tica_m = uimenu( plot_m, 'Label', 'Component maps' , 'userdata', onchannel);
uimenu( tica_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot2);
uimenu( tica_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot2);
uimenu( plot_m, 'Label', 'Component properties' , 'userdata', ondata , 'CallBack', cb_prop2);
uimenu( plot_m, 'Label', 'Component ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage2);
ERPC_m = uimenu( plot_m, 'Label', 'Component ERPs' , 'userdata', onepoch);
uimenu( ERPC_m, 'Label', 'With component maps' , 'CallBack', cb_envtopo1);
uimenu( ERPC_m, 'Label', 'With comp. maps (compare)' , 'CallBack', cb_envtopo2);
uimenu( ERPC_m, 'Label', 'In rectangular array' , 'CallBack', cb_plotdata2);
uimenu( plot_m, 'Label', 'Sum/Compare comp. ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp2);
stat_m = uimenu( plot_m, 'Label', 'Data statistics', 'Separator', 'on', 'userdata', ondata );
uimenu( stat_m, 'Label', 'Channel statistics' , 'CallBack', cb_signalstat1);
uimenu( stat_m, 'Label', 'Component statistics' , 'CallBack', cb_signalstat2);
uimenu( stat_m, 'Label', 'Event statistics' , 'CallBack', cb_eventstat);
spec_m = uimenu( plot_m, 'Label', 'Time-frequency transforms', 'Separator', 'on', 'userdata', ondata);
uimenu( spec_m, 'Label', 'Channel time-frequency' , 'CallBack', cb_timef1);
uimenu( spec_m, 'Label', 'Channel cross-coherence' , 'CallBack', cb_crossf1);
uimenu( spec_m, 'Label', 'Component time-frequency' , 'CallBack', cb_timef2,'Separator', 'on');
uimenu( spec_m, 'Label', 'Component cross-coherence' , 'CallBack', cb_crossf2);
uimenu( std_m, 'Label', 'Edit study info' , 'userdata', onstudy, 'CallBack', cb_study3);
uimenu( std_m, 'Label', 'Select/Edit study design(s)' , 'userdata', onstudy, 'CallBack', cb_studydesign);
uimenu( std_m, 'Label', 'Precompute channel measures' , 'userdata', onstudy, 'CallBack', cb_precomp, 'separator', 'on');
uimenu( std_m, 'Label', 'Plot channel measures' , 'userdata', onstudy, 'CallBack', cb_chanplot);
uimenu( std_m, 'Label', 'Precompute component measures' , 'userdata', onstudy, 'CallBack', cb_precomp2, 'separator', 'on');
clust_m = uimenu( std_m, 'Label', 'PCA clustering (original)' , 'userdata', onstudy);
uimenu( clust_m, 'Label', 'Build preclustering array' , 'userdata', onstudy, 'CallBack', cb_preclust);
uimenu( clust_m, 'Label', 'Cluster components' , 'userdata', onstudy, 'CallBack', cb_clust);
uimenu( std_m, 'Label', 'Edit/plot clusters' , 'userdata', onstudy, 'CallBack', cb_clustedit);
if ~iseeglabdeployed2
%newerVersionMenu = uimenu( help_m, 'Label', 'Upgrade to the Latest Version' , 'userdata', on, 'ForegroundColor', [0.6 0 0]);
uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'pophelp(''eeglab'');');
uimenu( help_m, 'Label', 'About EEGLAB help' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helphelp'');');
uimenu( help_m, 'Label', 'EEGLAB menus' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helpmenu'');','separator','on');
help_1 = uimenu( help_m, 'Label', 'EEGLAB functions', 'userdata', on);
uimenu( help_1, 'Label', 'Admin. functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpadmin'');');
uimenu( help_1, 'Label', 'Interactive pop_ functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helppop'');');
uimenu( help_1, 'Label', 'Signal processing functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpsigproc'');');
uimenu( help_1, 'Label', 'Group data (STUDY) functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstudy'');');
uimenu( help_1, 'Label', 'Time-frequency functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helptimefreq'');');
uimenu( help_1, 'Label', 'Statistical functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstatistics'');');
uimenu( help_1, 'Label', 'Graphic interface builder functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpgui'');');
uimenu( help_1, 'Label', 'Misc. command line functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpmisc'');');
uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);');
else
uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'abouteeglab;');
uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);');
end;
uimenu( help_m, 'Label', 'EEGLAB tutorial' , 'userdata', on, 'CallBack', 'tutorial;', 'Separator', 'on');
uimenu( help_m, 'Label', 'Email the EEGLAB team' , 'userdata', on, 'CallBack', 'web(''mailto:[email protected]'');');
end;
if iseeglabdeployed2
disp('Adding FIELDTRIP toolbox functions');
disp('Adding BIOSIG toolbox functions');
disp('Adding FILE-IO toolbox functions');
funcname = { 'eegplugin_VisEd' ...
'eegplugin_eepimport' ...
'eegplugin_bdfimport' ...
'eegplugin_brainmovie' ...
'eegplugin_bva_io' ...
'eegplugin_ctfimport' ...
'eegplugin_dipfit' ...
'eegplugin_erpssimport' ...
'eegplugin_fmrib' ...
'eegplugin_iirfilt' ...
'eegplugin_ascinstep' ...
'eegplugin_loreta' ...
'eegplugin_miclust' ...
'eegplugin_4dneuroimaging' };
for indf = 1:length(funcname)
try
vers = feval(funcname{indf}, gcf, trystrs, catchstrs);
disp(['EEGLAB: adding "' vers '" plugin' ]);
catch
feval(funcname{indf}, gcf, trystrs, catchstrs);
disp(['EEGLAB: adding plugin function "' funcname{indf} '"' ]);
end;
end;
else
pluginlist = [];
plugincount = 1;
p = mywhich('eeglab.m');
p = p(1:findstr(p,'eeglab.m')-1);
if strcmpi(p, './') || strcmpi(p, '.\'), p = [ pwd filesep ]; end;
% scan deactivated plugin folder
% ------------------------------
dircontent = dir(fullfile(p, 'deactivatedplugins'));
dircontent = { dircontent.name };
for index = 1:length(dircontent)
funcname = '';
pluginVersion = '';
if exist([p 'deactivatedplugins' filesep dircontent{index}]) == 7
if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..')
tmpdir = dir([ p 'deactivatedplugins' filesep dircontent{index} filesep 'eegplugin*.m' ]);
[ pluginName pluginVersion ] = parsepluginname(dircontent{index});
if ~isempty(tmpdir)
funcname = tmpdir(1).name(1:end-2);
end;
end;
else
if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm'
funcname = dircontent{index}(1:end-2); % remove .m
[ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2));
end;
end;
if ~isempty(pluginVersion)
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
pluginlist(plugincount).foldername = dircontent{index};
if ~isempty(funcname)
pluginlist(plugincount).funcname = funcname(10:end);
else pluginlist(plugincount).funcname = '';
end
if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_'
pluginlist(plugincount).funcname(1) = [];
end;
pluginlist(plugincount).status = 'deactivated';
plugincount = plugincount+1;
end;
end;
% scan plugin folder
% ------------------
dircontent = dir(fullfile(p, 'plugins'));
dircontent = { dircontent.name };
for index = 1:length(dircontent)
% find function
% -------------
funcname = '';
pluginVersion = [];
if exist([p 'plugins' filesep dircontent{index}]) == 7
if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..')
newpath = [ 'plugins' filesep dircontent{index} ];
tmpdir = dir([ p 'plugins' filesep dircontent{index} filesep 'eegplugin*.m' ]);
addpathifnotinlist(fullfile(eeglabpath, newpath));
[ pluginName pluginVersion ] = parsepluginname(dircontent{index});
if ~isempty(tmpdir)
%myaddpath(eeglabpath, tmpdir(1).name, newpath);
funcname = tmpdir(1).name(1:end-2);
end;
% special case of subfolder for Fieldtrip
% ---------------------------------------
if ~isempty(findstr(lower(dircontent{index}), 'fieldtrip'))
addpathifnotexist( fullfile(eeglabpath, newpath, 'compat') , 'electrodenormalize' );
addpathifnotexist( fullfile(eeglabpath, newpath, 'forward'), 'ft_sourcedepth.m');
addpathifnotexist( fullfile(eeglabpath, newpath, 'utilities'), 'ft_datatype.m');
ptopoplot = fileparts(mywhich('cbar'));
ptopoplot2 = fileparts(mywhich('topoplot'));
if ~isequal(ptopoplot, ptopoplot2)
addpath(ptopoplot);
end;
end;
% special case of subfolder for BIOSIG
% ------------------------------------
if ~isempty(findstr(lower(dircontent{index}), 'biosig')) && isempty(findstr(lower(dircontent{index}), 'biosigplot'))
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't200_FileAccess'), 'sopen.m');
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't250_ArtifactPreProcessingQualityControl'), 'regress_eog.m' );
addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 'doc'), 'DecimalFactors.txt');
end;
end;
else
if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm'
funcname = dircontent{index}(1:end-2); % remove .m
[ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2));
end;
end;
% execute function
% ----------------
if ~isempty(pluginVersion) || ~isempty(funcname)
if isempty(funcname)
disp([ 'EEGLAB: adding "' pluginName '" to the path; subfolders (if any) might be missing from the path' ]);
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
pluginlist(plugincount).foldername = dircontent{index};
pluginlist(plugincount).status = 'ok';
plugincount = plugincount+1;
else
pluginlist(plugincount).plugin = pluginName;
pluginlist(plugincount).version = pluginVersion;
vers = pluginlist(plugincount).version; % version
vers2 = '';
status = 'ok';
try,
%eval( [ 'vers2 =' funcname '(gcf, trystrs, catchstrs);' ]);
vers2 = feval(funcname, gcf, trystrs, catchstrs);
catch
try,
eval( [ funcname '(gcf, trystrs, catchstrs)' ]);
catch
disp([ 'EEGLAB: error while adding plugin "' funcname '"' ] );
disp([ ' ' lasterr] );
status = 'error';
end;
end;
pluginlist(plugincount).funcname = funcname(10:end);
pluginlist(plugincount).foldername = dircontent{index};
[tmp pluginlist(plugincount).versionfunc] = parsepluginname(vers2);
if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_'
pluginlist(plugincount).funcname(1) = [];
end;
if strcmpi(status, 'ok')
if isempty(vers), vers = pluginlist(plugincount).versionfunc; end;
if isempty(vers), vers = '?'; end;
fprintf('EEGLAB: adding "%s" v%s (see >> help %s)\n', ...
pluginlist(plugincount).plugin, vers, funcname);
end;
pluginlist(plugincount).status = status;
plugincount = plugincount+1;
end;
end;
end;
global PLUGINLIST;
PLUGINLIST = pluginlist;
end; % iseeglabdeployed2
% Path exception for BIOSIG (sending BIOSIG down into the path)
biosigpathlast; % fix str2double issue
if ~ismatlab, return; end;
% add other import ...
% --------------------
cb_others = [ 'pophelp(''troubleshooting_data_formats'');' ];
uimenu( import_m, 'Label', 'Using the FILE-IO interface', 'CallBack', cb_fileio, 'separator', 'on');
uimenu( import_m, 'Label', 'Using the BIOSIG interface' , 'CallBack', cb_biosig);
uimenu( import_m, 'Label', 'Troubleshooting data formats...', 'CallBack', cb_others);
% changing plugin menu color
% --------------------------
fourthsub_m = findobj('parent', tools_m);
plotsub_m = findobj('parent', plot_m);
importsub_m = findobj('parent', neuro_m);
epochsub_m = findobj('parent', epoch_m);
eventsub_m = findobj('parent', event_m);
editsub_m = findobj('parent', edit_m);
exportsub_m = findobj('parent', exportm);
filter_m = findobj('parent', filter_m);
icadefs; % containing PLUGINMENUCOLOR
if length(fourthsub_m) > 11, set(fourthsub_m(1:end-11), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(plotsub_m) > 17, set(plotsub_m (1:end-17), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(importsub_m) > 9, set(importsub_m(1:end-9) , 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(epochsub_m ) > 3 , set(epochsub_m (1:end-3 ), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(eventsub_m ) > 4 , set(eventsub_m (1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(exportsub_m) > 4 , set(exportsub_m(1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(editsub_m) > 10, set(editsub_m( 1:end-10), 'foregroundcolor', PLUGINMENUCOLOR); end;
if length(filter_m) > 3 , set(filter_m (1:end-1 ), 'foregroundcolor', PLUGINMENUCOLOR); end;
EEGMENU = uimenu( set_m, 'Label', '------', 'Enable', 'off');
eval('set(W_MAIN, ''userdat'', { EEGUSERDAT{1} EEGMENU javaobj });');
eeglab('redraw');
if nargout < 1
clear ALLEEG;
end;
%% automatic updater
try
[dummy eeglabVersionNumber currentReleaseDateString] = eeg_getversion;
if isempty(eeglabVersionNumber)
eeglabVersionNumber = 'dev';
end;
eeglabUpdater = up.updater(eeglabVersionNumber, 'http://sccn.ucsd.edu/eeglab/updater/latest_version.php', 'EEGLAB', currentReleaseDateString);
% create a new GUI item (e.g. under Help)
%newerVersionMenu = uimenu(help_m, 'Label', 'Upgrade to the Latest Version', 'visible', 'off', 'userdata', 'startup:on;study:on');
% set the callback to bring up the updater GUI
icadefs; % for getting background color
eeglabFolder = fileparts(mywhich('eeglab.m'));
%eeglabUpdater.menuItemHandle = []; %newerVersionMenu;
%eeglabUpdater.menuItemCallback = {@command_on_update_menu_click, eeglabUpdater, eeglabFolder, true, BACKEEGLABCOLOR};
% place it in the base workspace.
assignin('base', 'eeglabUpdater', eeglabUpdater);
% only start timer if the function is called from the command line
% (which means that the stack should only contain one element)
stackVar = dbstack;
if length(stackVar) == 1
if option_checkversion
eeglabUpdater.checkForNewVersion({'eeglab_event' 'setup'});
if strcmpi(eeglabVersionNumber, 'dev')
return;
end;
newMajorRevision = 0;
if ~isempty(eeglabUpdater.newMajorRevision)
fprintf('\nA new major version of EEGLAB (EEGLAB%s - beta) is now <a href="http://sccn.ucsd.edu/eeglab/">available</a>.\n', eeglabUpdater.newMajorRevision);
newMajorRevision = 1;
end;
if eeglabUpdater.newerVersionIsAvailable
eeglabv = num2str(eeglabUpdater.latestVersionNumber);
posperiod = find(eeglabv == '.');
if isempty(posperiod), posperiod = length(eeglabv)+1; eeglabv = [ eeglabv '.0' ]; end;
if length(eeglabv(posperiod+1:end)) < 2, eeglabv = [ eeglabv '0' ]; end;
%if length(eeglabv(posperiod+1:end)) < 3, eeglabv = [ eeglabv '0' ]; end;
eeglabv = [ eeglabv(1:posperiod+1) '.' eeglabv(posperiod+2) ]; %'.' eeglabv(posperiod+3) ];
stateWarning = warning('backtrace');
warning('backtrace', 'off');
if newMajorRevision
fprintf('\n');
warning( sprintf(['\nA critical revision of EEGLAB%d (%s) is also available <a href="%s">here</a>\n' ...
eeglabUpdater.releaseNotes 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations\n' ...
'You may disable this message in the Option menu but will miss critical updates.\n' ], ...
floor(eeglabVersionNumber), eeglabv, eeglabUpdater.downloadUrl, eeglabUpdater.releaseNotesUrl));
else
warning( sprintf(['\nA newer version of EEGLAB (%s) is available <a href="%s">here</a>\n' ...
eeglabUpdater.releaseNotes 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations.\n' ...
'You may disable this message in the Option menu but will miss critical updates.\n' ], ...
eeglabv, eeglabUpdater.downloadUrl, eeglabUpdater.releaseNotesUrl));
end;
warning('backtrace', stateWarning.state);
% make the Help menu item dark red
set(help_m, 'foregroundColor', [0.6, 0 0]);
elseif isempty(eeglabUpdater.lastTimeChecked)
fprintf('Could not check for the latest EEGLAB version (internet may be disconnected).\n');
fprintf('To prevent long startup time, disable checking for new EEGLAB version (FIle > Memory and other options).\n');
else
if ~newMajorRevision
fprintf('You are using the latest version of EEGLAB.\n');
else
fprintf('You are currently using the latest revision of EEGLAB%d (no critical update available).\n', floor(eeglabVersionNumber));
end;
end;
else
eeglabtimers = timerfind('name', 'eeglabupdater');
if ~isempty(eeglabtimers)
stop(eeglabtimers);
delete(eeglabtimers);
end;
% This is disabled because it cause Matlab to hang in case
% there is no connection or the connection is available but not
% usable
% start(timer('TimerFcn','try, eeglabUpdater.checkForNewVersion({''eeglab_event'' ''setup''}); catch, end; clear eeglabUpdater;', 'name', 'eeglabupdater', 'StartDelay', 20.0));
end;
end;
catch
if option_checkversion
fprintf('Updater could not be initialized.\n');
end;
end;
% REMOVED MENUS
%uimenu( tools_m, 'Label', 'Automatic comp. reject', 'enable', 'off', 'CallBack', '[EEG LASTCOM] = pop_rejcomp(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store(CURRENTSET); end;');
%uimenu( tools_m, 'Label', 'Reject (synthesis)' , 'Separator', 'on', 'CallBack', '[EEG LASTCOM] = pop_rejall(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store; end; eeglab(''redraw'');');
function command_on_update_menu_click(callerHandle, tmp, eeglabUpdater, installDirectory, goOneFolderLevelIn, backGroundColor)
postInstallCallbackString = 'clear all function functions; eeglab';
eeglabUpdater.launchGui(installDirectory, goOneFolderLevelIn, backGroundColor, postInstallCallbackString);
%
% --------------------
% draw the main figure
% --------------------
function tb = eeg_mainfig(onearg);
icadefs;
COLOR = BACKEEGLABCOLOR;
WINMINX = 17;
WINMAXX = 260;
WINYDEC = 13;
NBLINES = 16;
WINY = WINYDEC*NBLINES;
javaChatFlag = 1;
BORDERINT = 4;
BORDEREXT = 10;
comp = computer;
if strcmpi(comp(1:3), 'GLN') || strcmpi(comp(1:3), 'MAC') || strcmpi(comp(1:3), 'PCW')
FONTNAME = 'courier';
FONTSIZE = 8;
% Magnify figure under MATLAB 2012a
vers = version;
dotPos = find(vers == '.');
vernum = str2num(vers(1:dotPos(1)-1));
subvernum = str2num(vers(dotPos(1)+1:dotPos(2)-1));
if vernum > 7 || (vernum >= 7 && subvernum >= 14)
FONTSIZE = FONTSIZE+2;
WINMAXX = WINMAXX*1.3;
WINY = WINY*1.3;
end;
else
FONTNAME = '';
FONTSIZE = 11;
end;
hh = findobj('tag', 'EEGLAB');
if ~isempty(hh)
disp('EEGLAB warning: there can be only one EEGLAB window, closing old one');
close(hh);
end;
if strcmpi(onearg, 'remote')
figure( 'name', [ 'EEGLAB v' eeg_getversion ], ...
'numbertitle', 'off', ...
'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) 30 ], ...
'color', COLOR, ...
'Tag','EEGLAB', ...
'Userdata', {[] []});
%'resize', 'off', ...
return;
end;
W_MAIN = figure('Units','points', ...
... % 'Colormap','gray', ...
'PaperPosition',[18 180 576 432], ...
'PaperUnits','points', ...
'name', [ 'EEGLAB v' eeg_getversion ], ...
'numbertitle', 'off', ...
'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ], ...
'color', COLOR, ...
'Tag','EEGLAB', ...
'visible', 'off', ...
'Userdata', {[] []});
% 'resize', 'off', ...
% java chat
eeglab_options;
if option_chat == 1
if is_sccn
disp('Starting chat...');
tmpp = fileparts(mywhich('startpane.m'));
if isempty(tmpp) || ~ismatlab
disp('Cannot start chat');
tb = [];
else
disp(' ----------------------------------- ');
disp('| EEGLAB chat 0.9 |');
disp('| The chat currently only works |');
disp('| at the University of CA San Diego |');
disp(' ----------------------------------- ');
javaaddpath(fullfile(tmpp, 'Chat_with_pane.jar'));
eval('import client.EEGLABchat.*;');
eval('import client.VisualToolbar;');
eval('import java.awt.*;');
eval('import javax.swing.*;');
try
tb = VisualToolbar('137.110.244.26');
F = W_MAIN;
tb.setPreferredSize(Dimension(0, 75));
javacomponent(tb,'South',F);
javaclose = ['userdat = get(gcbf, ''userdata'');' ...
'try,'...
' tb = userdat{3};' ...
'clear userdat; delete(gcbf); tb.close; clear tb;'...
'catch,end;'];
set(gcf, 'CloseRequestFcn',javaclose);
refresh(F);
catch,
tb = [];
end;
end;
else
tb = [];
end;
else
tb = [];
end;
try,
set(W_MAIN, 'NextPlot','new');
catch, end;
if ismatlab
BackgroundColor = get(gcf, 'color'); %[0.701960784313725 0.701960784313725 0.701960784313725];
H_MAIN(1) = uicontrol('Parent',W_MAIN, ...
'Units','points', ...
'BackgroundColor',COLOR, ...
'ListboxTop',0, ...
'HorizontalAlignment', 'left',...
'Position',[BORDEREXT BORDEREXT (WINMINX+WINMAXX+2*BORDERINT) (WINY)], ...
'Style','frame', ...
'Tag','Frame1');
set(H_MAIN(1), 'unit', 'normalized');
geometry = { [1] [1] [1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1] };
listui = { { 'style', 'text', 'string', 'Parameters of the current set', 'tag', 'win0' } { } ...
{ 'style', 'text', 'tag', 'win1', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win2', 'string', 'Channels per frame', 'userdata', 'datinfo'} ...
{ 'style', 'text', 'tag', 'val2', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win3', 'string', 'Frames per epoch', 'userdata', 'datinfo'} ...
{ 'style', 'text', 'tag', 'val3', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win4', 'string', 'Epochs', 'userdata', 'datinfo'} ...
{ 'style', 'text', 'tag', 'val4', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win5', 'string', 'Events', 'userdata', 'datinfo'} ...
{ 'style', 'text', 'tag', 'val5', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win6', 'string', 'Sampling rate (Hz)', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val6', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win7', 'string', 'Epoch start (sec)', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val7', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win8', 'string', 'Epoch end (sec)', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val8', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win9', 'string', 'Average reference', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val9', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win10', 'string', 'Channel locations', 'userdata', 'datinfo'} ...
{ 'style', 'text', 'tag', 'val10', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win11', 'string', 'ICA weights', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val11', 'string', ' ', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'win12', 'string', 'Dataset size (Mb)', 'userdata', 'datinfo' } ...
{ 'style', 'text', 'tag', 'val12', 'string', ' ', 'userdata', 'datinfo' } {} };
supergui(gcf, geometry, [], listui{:});
geometry = { [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] };
listui = { { } ...
{ } ...
{ 'style', 'text', 'tag', 'mainwin1', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin2', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin3', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin4', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin5', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin6', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin7', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin8', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin9', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin10', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin11', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin12', 'string', ' ', 'userdata', 'fullline' } ...
{ 'style', 'text', 'tag', 'mainwin13', 'string', ' ', 'userdata', 'fullline' } {} };
supergui(gcf, geometry, [], listui{:});
titleh = findobj('parent', gcf, 'tag', 'win0');
alltexth = findobj('parent', gcf, 'style', 'text');
alltexth = setdiff_bc(alltexth, titleh);
set(gcf, 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ]);
set(titleh, 'fontsize', TEXT_FONTSIZE_L, 'fontweight', 'bold');
set(alltexth, 'fontname', FONTNAME, 'fontsize', FONTSIZE);
set(W_MAIN, 'visible', 'on');
end;
return;
% eeglab(''redraw'')() - Update EEGLAB menus based on values of global variables.
%
% Usage: >> eeglab(''redraw'')( );
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeg_global(), eeglab()
% WHEN THIS FUNCTION WAS SEPARATED
% Revision 1.21 2002/04/23 19:09:25 arno
% adding automatic dataset search
% Revision 1.20 2002/04/18 20:02:23 arno
% retrIeve
% Revision 1.18 2002/04/18 16:28:28 scott
% EEG.averef printed as 'Yes' or 'No' -sm
% Revision 1.16 2002/04/18 16:03:15 scott
% editted "Events/epoch info (nb) -> Events -sm
% Revision 1.14 2002/04/18 14:46:58 scott
% editted main window help msg -sm
% Revision 1.10 2002/04/18 03:02:17 scott
% edited opening instructions -sm
% Revision 1.9 2002/04/11 18:23:33 arno
% Oups, typo which crashed EEGLAB
% Revision 1.8 2002/04/11 18:07:59 arno
% adding average reference variable
% Revision 1.7 2002/04/11 17:49:40 arno
% corrected operator precedence problem
% Revision 1.6 2002/04/11 15:36:55 scott
% added parentheses to final ( - & - ), line 84. ARNO PLEASE CHECK -sm
% Revision 1.5 2002/04/11 15:34:50 scott
% put isempty(CURRENTSET) first in line ~80 -sm
% Revision 1.4 2002/04/11 15:31:47 scott
% added test isempty(CURRENTSET) line 78 -sm
% Revision 1.3 2002/04/11 01:41:27 arno
% checking dataset ... and inteligent menu update
% Revision 1.2 2002/04/09 20:47:41 arno
% introducing event number into gui
function updatemenu();
eeg_global;
W_MAIN = findobj('tag', 'EEGLAB');
EEGUSERDAT = get(W_MAIN, 'userdata');
H_MAIN = EEGUSERDAT{1};
EEGMENU = EEGUSERDAT{2};
if length(EEGUSERDAT) > 2
tb = EEGUSERDAT{3};
else tb = [];
end;
if ~isempty(tb) && ~isstr(tb)
eval('tb.RefreshToolbar();');
end;
if exist('CURRENTSET') ~= 1, CURRENTSET = 0; end;
if isempty(ALLEEG), ALLEEG = []; end;
if isempty(EEG), EEG = []; end;
% test if the menu is present
try
figure(W_MAIN);
set_m = findobj( 'parent', W_MAIN, 'Label', 'Datasets');
catch, return; end;
index = 1;
indexmenu = 1;
MAX_SET = max(length( ALLEEG ), length(EEGMENU)-1);
tmp = warning;
warning off;
clear functions;
warning(tmp);
eeglab_options;
if isempty(ALLEEG) && ~isempty(EEG) && ~isempty(EEG.data)
ALLEEG = EEG;
end;
% setting the dataset menu
% ------------------------
while( index <= MAX_SET)
try
set( EEGMENU(index), 'Label', '------', 'checked', 'off');
catch,
if mod(index, 30) == 0
tag = [ 'More (' int2str(index/30) ') ->' ];
tmp_m = findobj('label', tag);
if isempty(tmp_m)
set_m = uimenu( set_m, 'Label', tag, 'userdata', 'study:on');
else set_m = tmp_m;
end;
end;
try
set( EEGMENU(index), 'Label', '------', 'checked', 'off');
catch, EEGMENU(index) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end;
end;
set( EEGMENU(index), 'Enable', 'on', 'separator', 'off' );
try, ALLEEG(index).data;
if ~isempty( ALLEEG(index).data)
cb_retrieve = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', ' int2str(index) ', ''study'', ~isempty(STUDY)+0);' ...
'if CURRENTSTUDY & ~isempty(LASTCOM), CURRENTSTUDY = 0; LASTCOM = [ ''CURRENTSTUDY = 0;'' LASTCOM ]; end; eegh(LASTCOM);' ...
'eeglab(''redraw'');' ];
menutitle = sprintf('Dataset %d:%s', index, ALLEEG(index).setname);
set( EEGMENU(index), 'Label', menutitle, 'userdata', 'study:on');
set( EEGMENU(index), 'CallBack', cb_retrieve );
set( EEGMENU(index), 'Enable', 'on' );
if any(index == CURRENTSET), set( EEGMENU(index), 'checked', 'on' ); end;
end;
catch, end;
index = index+1;
end;
hh = findobj( 'parent', set_m, 'Label', '------');
set(hh, 'Enable', 'off');
% menu for selecting several datasets
% -----------------------------------
if index ~= 0
cb_select = [ 'nonempty = find(~cellfun(''isempty'', { ALLEEG.data } ));' ...
'tmpind = pop_chansel({ ALLEEG(nonempty).setname }, ''withindex'', nonempty);' ...
'if ~isempty(tmpind),' ...
' [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', nonempty(tmpind), ''study'', ~isempty(STUDY)+0);' ...
' eegh(LASTCOM);' ...
' eeglab(''redraw'');' ...
'end;' ...
'clear tmpind nonempty;' ];
if MAX_SET == length(EEGMENU), EEGMENU(end+1) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end;
set(EEGMENU(end), 'enable', 'on', 'Label', 'Select multiple datasets', ...
'callback', cb_select, 'separator', 'on', 'userdata', 'study:on');
end;
% STUDY consistency
% -----------------
exist_study = 0;
if exist('STUDY') & exist('CURRENTSTUDY')
% if study present, check study consistency with loaded datasets
% --------------------------------------------------------------
if ~isempty(STUDY)
if length(ALLEEG) > length(STUDY.datasetinfo) || ~isfield(ALLEEG, 'data') || any(cellfun('isempty', {ALLEEG.data}))
if strcmpi(STUDY.saved, 'no')
res = questdlg2( strvcat('The study is not compatible with the datasets present in memory', ...
'It is self consistent but EEGLAB is not be able to process it.', ...
'Do you wish to save the study as it is (EEGLAB will prompt you to', ...
'enter a file name) or do you wish to remove it'), 'Study inconsistency', 'Save and remove', 'Remove', 'Remove' );
if strcmpi(res, 'Remove')
STUDY = [];
CURRENTSTUDY = 0;
else
pop_savestudy(STUDY, ALLEEG);
STUDY = [];
CURRENTSTUDY = 0;
end;
else
warndlg2( strvcat('The study was not compatible any more with the datasets present in memory.', ...
'Since it had not changed since last saved, it was simply removed from', ...
'memory.') );
STUDY = [];
CURRENTSTUDY = 0;
end;
end;
end;
if ~isempty(STUDY)
exist_study = 1;
end;
end;
% menu for selecting STUDY set
% ----------------------------
if exist_study
cb_select = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', [STUDY.datasetinfo.index], ''study'', 1);' ...
'if ~isempty(LASTCOM), CURRENTSTUDY = 1; LASTCOM = [ LASTCOM ''CURRENTSTUDY = 1;'' ]; end;' ...
'eegh(LASTCOM);' ...
'eeglab(''redraw'');' ];
tmp_m = findobj('label', 'Select the study set');
delete(tmp_m); % in case it is not at the end
tmp_m = uimenu( set_m, 'Label', 'Select the study set', 'Enable', 'on', 'userdata', 'study:on');
set(tmp_m, 'enable', 'on', 'callback', cb_select, 'separator', 'on');
else
delete( findobj('label', 'Select the study set') );
end;
EEGUSERDAT{2} = EEGMENU;
set(W_MAIN, 'userdata', EEGUSERDAT);
if (isempty(CURRENTSET) | length(ALLEEG) < CURRENTSET(1) | CURRENTSET(1) == 0 | isempty(ALLEEG(CURRENTSET(1)).data))
CURRENTSET = 0;
for index = 1:length(ALLEEG)
if ~isempty(ALLEEG(index).data)
CURRENTSET = index;
break;
end;
end;
if CURRENTSET ~= 0
eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ])
[EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET);
else
EEG = eeg_emptyset;
end;
end;
if (isempty(EEG) | isempty(EEG(1).data)) & CURRENTSET(1) ~= 0
eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ])
[EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET);
end;
% test if dataset has changed
% ---------------------------
if length(EEG) == 1
if ~isempty(ALLEEG) & CURRENTSET~= 0 & ~isequal(EEG.data, ALLEEG(CURRENTSET).data) & ~isnan(EEG.data(1))
% the above comparison does not work for ome structures
%tmpanswer = questdlg2(strvcat('The current EEG dataset has changed. What should eeglab do with the changes?', ' '), ...
% 'Dataset change detected', ...
% 'Keep changes', 'Delete changes', 'New dataset', 'Make new dataset');
disp('Warning: for some reason, the backup dataset in EEGLAB memory does not');
disp(' match the current dataset. The dataset in memory has been overwritten');
[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);');
%if tmpanswer(1) == 'D' % delete changes
% [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET);
% eegh('[EEG ALLEEG] = eeg_retrieve( ALLEEG, CURRENTSET);');
%elseif tmpanswer(1) == 'K' % keep changes
% [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);
% eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);');
%else % make new dataset
% [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
% eegh(LASTCOM);
% MAX_SET = max(length( ALLEEG ), length(EEGMENU));
%end;
end;
end;
% print some information on the main figure
% ------------------------------------------
g = myguihandles(gcf);
if ~isfield(g, 'win0') % no display
return;
end;
study_selected = 0;
if exist('STUDY') & exist('CURRENTSTUDY')
if CURRENTSTUDY == 1, study_selected = 1; end;
end;
menustatus = {};
if study_selected
menustatus = { menustatus{:} 'study' };
hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off');
hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on');
% head string
% -----------
set( g.win0, 'String', sprintf('STUDY set: %s', STUDY.name) );
% dataset type
% ------------
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous';
elseif datasettype(1) == 1, datasettype = 'epoched and continuous';
else datasettype = 'epoched';
end;
% number of channels and channel locations
% ----------------------------------------
chanlen = unique_bc( [ EEG.nbchan ] );
chanlenstr = vararg2str( mattocell(chanlen) );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(anyempty) == 2, chanlocs = 'mixed, yes and no';
elseif anyempty == 0, chanlocs = 'yes';
else chanlocs = 'no';
end;
% ica weights
% -----------
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 2, studystatus = 'Missing ICA dec.';
elseif anyempty == 0, studystatus = 'Ready to precluster';
else studystatus = 'Missing ICA dec.';
end;
% consistency & other parameters
% ------------------------------
[EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency
[EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency
[EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency
totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events
totsize = whos('STUDY', 'ALLEEG'); % total size
if isempty(STUDY.session), sessionstr = ''; else sessionstr = vararg2str(STUDY.session); end;
if isempty(STUDY.condition), condstr = ''; else condstr = vararg2str(STUDY.condition); end;
% determine study status
% ----------------------
if isfield(STUDY.etc, 'preclust')
if ~isempty( STUDY.etc.preclust )
studystatus = 'Pre-clustered';
elseif length(STUDY.cluster) > 1
studystatus = 'Clustered';
end;
elseif length(STUDY.cluster) > 1
studystatus = 'Clustered';
end;
% text
% ----
set( g.win2, 'String', 'Study task name');
set( g.win3, 'String', 'Nb of subjects');
set( g.win4, 'String', 'Nb of conditions');
set( g.win5, 'String', 'Nb of sessions');
set( g.win6, 'String', 'Nb of groups');
set( g.win7, 'String', 'Epoch consistency');
set( g.win8, 'String', 'Channels per frame');
set( g.win9, 'String', 'Channel locations');
set( g.win10, 'String', 'Clusters');
set( g.win11, 'String', 'Status');
set( g.win12, 'String', 'Total size (Mb)');
% values
% ------
fullfilename = fullfile( STUDY.filepath, STUDY.filename);
if length(fullfilename) > 26
set( g.win1, 'String', sprintf('Study filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) ));
else
set( g.win1, 'String', sprintf('Study filename: %s\n' , fullfilename));
end;
condconsist = std_checkconsist(STUDY, 'uniform', 'condition');
groupconsist = std_checkconsist(STUDY, 'uniform', 'group');
sessconsist = std_checkconsist(STUDY, 'uniform', 'session');
txtcond = fastif(condconsist , ' per subject', ' (some missing)');
txtgroup = fastif(groupconsist, ' per subject', ' (some missing)');
txtsess = fastif(sessconsist , ' per subject', ' (some missing)');
set( g.val2, 'String', STUDY.task);
set( g.val3, 'String', int2str(max(1, length(STUDY.subject))));
set( g.val4, 'String', [ int2str(max(1, length(STUDY.condition))) txtcond ]);
set( g.val5, 'String', [ int2str(max(1, length(STUDY.session))) txtsess ]);
set( g.val6, 'String', [ int2str(max(1, length(STUDY.group))) txtgroup ]);
set( g.val7, 'String', epochconsist);
set( g.val8, 'String', chanlenstr);
set( g.val9, 'String', chanlocs);
set( g.val10, 'String', length(STUDY.cluster));
set( g.val11, 'String', studystatus);
set( g.val12, 'String', num2str(round(sum( [ totsize.bytes] )/1E6*10)/10));
elseif (exist('EEG') == 1) & ~isnumeric(EEG) & ~isempty(EEG(1).data)
hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off');
hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on');
if length(EEG) > 1 % several datasets
menustatus = { menustatus{:} 'multiple_datasets' };
% head string
% -----------
strsetnum = 'Datasets ';
for i = CURRENTSET
strsetnum = [ strsetnum int2str(i) ',' ];
end;
strsetnum = strsetnum(1:end-1);
set( g.win0, 'String', strsetnum);
% dataset type
% ------------
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous';
elseif datasettype(1) == 1, datasettype = 'epoched and continuous';
else datasettype = 'epoched';
end;
% number of channels and channel locations
% ----------------------------------------
chanlen = unique_bc( [ EEG.nbchan ] );
chanlenstr = vararg2str( mattocell(chanlen) );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(anyempty) == 2, chanlocs = 'mixed, yes and no';
elseif anyempty == 0, chanlocs = 'yes';
else chanlocs = 'no';
end;
% ica weights
% -----------
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 2, icaweights = 'mixed, yes and no';
elseif anyempty == 0, icaweights = 'yes';
else icaweights = 'no';
end;
% consistency & other parameters
% ------------------------------
[EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency
[EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency
[EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency
totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events
srate = vararg2str( mattocell( unique( [ EEG.srate ] ) )); % sampling rate
totsize = whos('EEG'); % total size
% text
% ----
set( g.win2, 'String', 'Number of datasets');
set( g.win3, 'String', 'Dataset type');
set( g.win4, 'String', 'Epoch consistency');
set( g.win5, 'String', 'Channels per frame');
set( g.win6, 'String', 'Channel consistency');
set( g.win7, 'String', 'Channel locations');
set( g.win8, 'String', 'Events (total)');
set( g.win9, 'String', 'Sampling rate (Hz)');
set( g.win10, 'String', 'ICA weights');
set( g.win11, 'String', 'Identical ICA');
set( g.win12, 'String', 'Total size (Mb)');
% values
% ------
set( g.win1, 'String', sprintf('Groupname: -(soon)-\n'));
set( g.val2, 'String', int2str(length(EEG)));
set( g.val3, 'String', datasettype);
set( g.val4, 'String', epochconsist);
set( g.val5, 'String', chanlenstr);
set( g.val6, 'String', chanconsist);
set( g.val7, 'String', chanlocs);
set( g.val8, 'String', totevents);
set( g.val9, 'String', srate);
set( g.val10, 'String', icaweights);
set( g.val11, 'String', icaconsist);
set( g.val12, 'String', num2str(round(totsize.bytes/1E6*10)/10));
else % one continous dataset selected
menustatus = { menustatus{:} 'continuous_dataset' };
% text
% ----
set( g.win2, 'String', 'Channels per frame');
set( g.win3, 'String', 'Frames per epoch');
set( g.win4, 'String', 'Epochs');
set( g.win5, 'String', 'Events');
set( g.win6, 'String', 'Sampling rate (Hz)');
set( g.win7, 'String', 'Epoch start (sec)');
set( g.win8, 'String', 'Epoch end (sec)');
set( g.win9, 'String', 'Reference');
set( g.win10, 'String', 'Channel locations');
set( g.win11, 'String', 'ICA weights');
set( g.win12, 'String', 'Dataset size (Mb)');
if CURRENTSET == 0, strsetnum = '';
else strsetnum = ['#' int2str(CURRENTSET) ': '];
end;
maxchar = 28;
if ~isempty( EEG.setname )
if length(EEG.setname) > maxchar+2
set( g.win0, 'String', [strsetnum EEG.setname(1:min(maxchar,length(EEG.setname))) '...' ]);
else set( g.win0, 'String', [strsetnum EEG.setname ]);
end;
else
set( g.win0, 'String', [strsetnum '(no dataset name)' ] );
end;
fullfilename = fullfile(EEG.filepath, EEG.filename);
if ~isempty(fullfilename)
if length(fullfilename) > 26
set( g.win1, 'String', sprintf('Filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) ));
else
set( g.win1, 'String', sprintf('Filename: %s\n', fullfilename));
end;
else
set( g.win1, 'String', sprintf('Filename: none\n'));
end;
set( g.val2, 'String', int2str(fastif(isempty(EEG.data), 0, size(EEG.data,1))));
set( g.val3, 'String', int2str(EEG.pnts));
set( g.val4, 'String', int2str(EEG.trials));
set( g.val5, 'String', fastif(isempty(EEG.event), 'none', int2str(length(EEG.event))));
set( g.val6, 'String', int2str( round(EEG.srate)) );
if round(EEG.xmin) == EEG.xmin & round(EEG.xmax) == EEG.xmax
set( g.val7, 'String', sprintf('%d\n', EEG.xmin));
set( g.val8, 'String', sprintf('%d\n', EEG.xmax));
else
set( g.val7, 'String', sprintf('%6.3f\n', EEG.xmin));
set( g.val8, 'String', sprintf('%6.3f\n', EEG.xmax));
end;
% reference
if isfield(EEG(1).chanlocs, 'ref')
[curref tmp allinds] = unique_bc( { EEG(1).chanlocs.ref });
maxind = 1;
for ind = unique_bc(allinds)
if length(find(allinds == ind)) > length(find(allinds == maxind))
maxind = ind;
end;
end;
curref = curref{maxind};
if isempty(curref), curref = 'unknown'; end;
else curref = 'unknown';
end;
set( g.val9, 'String', curref);
if isempty(EEG.chanlocs)
set( g.val10, 'String', 'No');
else
if ~isfield(EEG.chanlocs, 'theta') | all(cellfun('isempty', { EEG.chanlocs.theta }))
set( g.val10, 'String', 'No (labels only)');
else
set( g.val10, 'String', 'Yes');
end;
end;
set( g.val11, 'String', fastif(isempty(EEG.icasphere), 'No', 'Yes'));
tmp = whos('EEG');
if ~isa(EEG.data, 'memmapdata') && ~isa(EEG.data, 'mmo')
set( g.val12, 'String', num2str(round(tmp.bytes/1E6*10)/10));
else
set( g.val12, 'String', [ num2str(round(tmp.bytes/1E6*10)/10) ' (file mapped)' ]);
end;
if EEG.trials > 1 || EEG.xmin ~= 0
menustatus = { menustatus{:} 'epoched_dataset' };
else
menustatus = { menustatus{:} 'continuous_dataset' };
end
if ~isfield(EEG.chanlocs, 'theta')
menustatus = { menustatus{:} 'chanloc_absent' };
end;
if isempty(EEG.icaweights)
menustatus = { menustatus{:} 'ica_absent' };
end;
end;
else
menustatus = { menustatus{:} 'startup' };
hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'on');
hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'off');
set( g.win0, 'String', 'No current dataset');
set( g.mainwin1, 'String', '- Create a new or load an existing dataset:');
set( g.mainwin2, 'String', ' Use "File > Import data" (new)');
set( g.mainwin3, 'String', ' Or "File > Load existing dataset" (old)');
set( g.mainwin4, 'String', '- If new,');
set( g.mainwin5, 'String', ' "File > Import epoch info" (data epochs) else');
set( g.mainwin6, 'String', ' "File > Import event info" (continuous data)');
set( g.mainwin7, 'String', ' "Edit > Dataset info" (add/edit dataset info)');
set( g.mainwin8, 'String', ' "File > Save dataset" (save dataset)');
set( g.mainwin9, 'String', '- Prune data: "Edit > Select data"');
set( g.mainwin10,'String', '- Reject data: "Tools > Reject continuous data"');
set( g.mainwin11,'String', '- Epoch data: "Tools > Extract epochs"');
set( g.mainwin12,'String', '- Remove baseline: "Tools > Remove baseline"');
set( g.mainwin13,'String', '- Run ICA: "Tools > Run ICA"');
end;
% ERPLAB
if exist('ALLERP') == 1 && ~isempty(ALLERP)
menustatus = { menustatus{:} 'erp_dataset' };
end;
% enable selected menu items
% --------------------------
allmenus = findobj( W_MAIN, 'type', 'uimenu');
allstrs = get(allmenus, 'userdata');
if any(strcmp(menustatus, 'startup'))
set(allmenus, 'enable', 'on');
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''startup:off''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'off');
elseif any(strcmp(menustatus, 'study'))
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);');
set(allmenus , 'enable', 'off');
set(allmenus(indmatchvar), 'enable', 'on');
elseif any(strcmp(menustatus, 'multiple_datasets'))
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);');
set(allmenus , 'enable', 'off');
set(allmenus(indmatchvar), 'enable', 'on');
set(findobj('parent', W_MAIN, 'label', 'Study'), 'enable', 'off');
% --------------------------------
% Javier Lopez-Calderon for ERPLAB
elseif any(strcmp(menustatus, 'epoched_dataset'))
set(allmenus, 'enable', 'on');
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''epoch:off''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'off');
% end, Javier Lopez-Calderon for ERPLAB
% --------------------------------
elseif any(strcmp(menustatus, 'continuous_dataset'))
set(allmenus, 'enable', 'on');
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''continuous:off''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'off');
end;
if any(strcmp(menustatus, 'chanloc_absent'))
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''chanloc:on''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'off');
end;
if any(strcmp(menustatus, 'ica_absent'))
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''ica:on''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'off');
end;
% --------------------------------
% Javier Lopez-Calderon for ERPLAB
if any(strcmp(menustatus, 'erp_dataset'))
eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''erpset:on''))), allstrs);');
set(allmenus(indmatchvar), 'enable', 'on');
end
% end, Javier Lopez-Calderon for ERPLAB
% --------------------------------
% adjust title extent
% -------------------
poswin0 = get(g.win0, 'position');
extwin0 = get(g.win0, 'extent');
set(g.win0, 'position', [poswin0(1:2) extwin0(3) extwin0(4)]);
% adjust all font sizes (RMC fix MATLAB 2014 compatibility)
% -------------------
handlesname = fieldnames(g);
for i = 1:length(handlesname)
if isprop(eval(['g.' handlesname{i}]),'Style') & ~strcmp(handlesname{i},'win0')
propval = get(eval(['g.' handlesname{i}]), 'Style');
if strcmp(propval,'text')
set(eval(['g.' handlesname{i}]),'FontSize',TEXT_FONTSIZE);
end
end
end
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
function g = myguihandles(fig)
g = [];
hh = findobj('parent', gcf);
for index = 1:length(hh)
if ~isempty(get(hh(index), 'tag'))
g = setfield(g, get(hh(index), 'tag'), hh(index));
end;
end;
function rmpathifpresent(newpath);
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpath = [ newpath ';' ];
else
newpath = [ newpath ':' ];
end;
if ismatlab
p = matlabpath;
else p = path;
end;
ind = strfind(p, newpath);
if ~isempty(ind)
rmpath(newpath);
end;
% add path only if it is not already in the list
% ----------------------------------------------
function addpathifnotinlist(newpath);
comp = computer;
if strcmpi(comp(1:2), 'PC')
newpathtest = [ newpath ';' ];
else
newpathtest = [ newpath ':' ];
end;
if ismatlab
p = matlabpath;
else p = path;
end;
ind = strfind(p, newpathtest);
if isempty(ind)
if exist(newpath) == 7
addpath(newpath);
end;
end;
function addpathifnotexist(newpath, functionname);
tmpp = mywhich(functionname);
if isempty(tmpp)
addpath(newpath);
end;
% find a function path and add path if not present
% ------------------------------------------------
function myaddpath(eeglabpath, functionname, pathtoadd);
tmpp = mywhich(functionname);
tmpnewpath = [ eeglabpath pathtoadd ];
if ~isempty(tmpp)
tmpp = tmpp(1:end-length(functionname));
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
%disp([ tmpp ' | ' tmpnewpath '(' num2str(~strcmpi(tmpnewpath, tmpp)) ')' ]);
if ~strcmpi(tmpnewpath, tmpp)
warning('off', 'MATLAB:dispatcher:nameConflict');
addpath(tmpnewpath);
warning('on', 'MATLAB:dispatcher:nameConflict');
end;
else
%disp([ 'Adding new path ' tmpnewpath ]);
addpathifnotinlist(tmpnewpath);
end;
function val = iseeglabdeployed2;
%val = 1; return;
if exist('isdeployed')
val = isdeployed;
else val = 0;
end;
function buildhelpmenu;
% parse plugin function name
% --------------------------
function [name, vers] = parsepluginname(dirName);
ind = find( dirName >= '0' & dirName <= '9' );
if isempty(ind)
name = dirName;
vers = '';
else
ind = length(dirName);
while ind > 0 && ((dirName(ind) >= '0' & dirName(ind) <= '9') || dirName(ind) == '.' || dirName(ind) == '_')
ind = ind - 1;
end;
name = dirName(1:ind);
vers = dirName(ind+1:end);
vers(find(vers == '_')) = '.';
end;
% required here because path not added yet
% to the admin folder
function res = ismatlab;
v = version;
if v(1) > '4'
res = 1;
else
res = 0;
end;
function res = mywhich(varargin);
try
res = which(varargin{:});
catch
fprintf('Warning: permission error accesssing %s\n', varargin{1});
end;
|
github
|
lcnbeapp/beapp-master
|
display.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/display.m
| 1,180 |
utf_8
|
d3d679b5764eca6d062540923f669f7b
|
% display() - display an EEG data class underlying structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function b = display(a)
i.type = '()';
i.subs = { ':' ':' ':' };
b = subsref(a, i); % note that subsref cannot be called directly
return;
%struct(a)
%return;
if ~strcmpi(a.fileformat, 'transposed')
a.data.data.x;
else
permute(a, [3 1 2]);
end;
|
github
|
lcnbeapp/beapp-master
|
reshape.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/reshape.m
| 1,449 |
utf_8
|
d59a7e256f6fc43fe77f3be9319fcc46
|
% reshape() - reshape of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function a = reshape(a,d1,d2,d3)
% decode length
% -------------
if nargin > 3
d1 = [ d1 d2 d3 ];
elseif nargin > 2
d1 = [ d1 d2 ];
end;
if prod(size(a)) ~= prod(d1)
error('Wrong dimensions for reshaping');
end;
if ~strcmpi(a.fileformat, 'transposed')
a.data.format{2} = d1;
else
if length(d1) == 1
a.data.format{2} = d1;
elseif length(d1) == 2
a.data.format{2} = [d1(2) d1(1)];
else
a.data.format{2} = d1([2 3 1]);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
end.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/end.m
| 901 |
utf_8
|
0e38d125a547083cb574fbd3bb455fbd
|
% end() - last index to memmapdata array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function s = end(a, k, n);
s = size(a, k);
|
github
|
lcnbeapp/beapp-master
|
subsasgn.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/subsasgn.m
| 1,590 |
utf_8
|
6b2894eb17dab5aae0637b84992ffb7d
|
% subsasgn() - define index assignment for eegdata objects
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function b = subsasgn(a,index,val)
i.type = '()';
i.subs = { ':' ':' ':' };
b = subsref(a, i); % note that subsref cannot be called directly
c = subsref(val, i);
b = builtin('subsasgn', b, index, c);
return;
switch index.type
case '()'
switch length(index.subs)
case 1, a.data(index.subs{1}) = val;
case 2, a.data(index.subs{1}, index.subs{2}) = val;
case 3, a.data(index.subs{1}, index.subs{2}, index.subs{3}) = val;
case 4, a.data(index.subs{1}, index.subs{2}, index.subs{3}, index.subs{4}) = val;
end;
case '.'
switch index.subs
case 'srate'
a.srate = val;
case 'nbchan'
a.nbchan = val;
otherwise
error('Invalid field name')
end
end
|
github
|
lcnbeapp/beapp-master
|
isnumeric.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/isnumeric.m
| 877 |
utf_8
|
34baf204e1b984ee69cf7f462fe2e524
|
% isnumeric() - returns 1
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function r = isnumeric(a)
r = 1;
|
github
|
lcnbeapp/beapp-master
|
length.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/length.m
| 913 |
utf_8
|
f0841237745a123f3215e00164cc4a1a
|
% length() - length of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function s = length(a)
s = size(a,1);
|
github
|
lcnbeapp/beapp-master
|
sum.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/sum.m
| 1,913 |
utf_8
|
dbd7353e16ccf6a1a0b69875cd9050cb
|
% sum() - sum of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [s] = sum(a,dim)
if nargin < 2
dim = 1;
end;
%b = (:,:,:);
if ~strcmpi(a.fileformat, 'transposed')
s = sum(a.data.data.x, dim);
else
alldim = [3 1 2];
if length(size(a)) == 3
dim = alldim(dim);
s = sum(a.data.data.x, dim);
s = permute(s, [3 1 2]);
else
if dim == 1
dim = 2;
else dim = 1;
end;
s = sum(a.data.data.x, dim)';
end;
end;
return;
% do pnts by pnts if dim = 1
% if dim == 1 & length(
%
% s = zeros(size(a,2), size(a,3));
% for i=1:size(a,2)
% s(i,:) = mean(a.data.data.x(:,i,:));
% end;
% elseif dim == 1
% s = zeros(size(a,1), size(a,1));
% for i=1:size(a,1)
% s(i,:) = mean(a.data.data.x(:,:,:));
% end;
%
%
% s = builtin('sum', rand(10,10), dim);
%if length(size(a)) > 2
%else s = sum(a(:,:,:), dim);
%end;
|
github
|
lcnbeapp/beapp-master
|
size.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/size.m
| 1,383 |
utf_8
|
c7033b3ab1405ded2c8794f2c214beb9
|
% size() - size of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [s s2 s3] = size(a,dim)
if isnumeric(a.data),
s = size(a.data)
else
s = a.data.format{2};
if strcmpi(a.fileformat, 'transposed')
if length(s) == 2, s = s([2 1]);
elseif length(s) == 3
s = [s(3) s(1) s(2)];
end;
end;
end;
if nargin > 1
s = [s 1];
s = s(dim);
end;
if nargout > 2
s3 = s(3);
end;
if nargout > 1
s2 = s(2);
s = s(1);
end;
|
github
|
lcnbeapp/beapp-master
|
subsref.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/subsref.m
| 4,622 |
utf_8
|
096fd75b6454f11ffee5a172000a64c1
|
% subsref() - index eegdata class
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function b = subsref(a,s)
if s(1).type == '.'
b = builtin('subsref', struct(a), s); return;
end;
subs = s(1).subs;
finaldim = cellfun('length', subs);
% one dimension input
% -------------------
if length(s(1).subs) == 1
if isstr(subs{1})
subs{1} = [1:size(a,1)];
subs{2} = [1:size(a,2)];
if ndims(a) == 3, subs{3} = [1:size(a,3)]; end;
finaldim = prod(size(a));
end;
% two dimension input
% -------------------
elseif length(s(1).subs) == 2
if isstr(subs{1}), subs{1} = [1:size(a,1)]; end;
if isstr(subs{2}),
subs{2} = [1:size(a,2)];
if ndims(a) == 3, subs{3} = [1:size(a,3)]; end;
end;
if length(subs) == 3
finaldim = [ length(subs{1}) length(subs{2})*length(subs{3}) ];
else finaldim = [ length(subs{1}) length(subs{2}) ];
end;
% three dimension input
% ---------------------
elseif length(s(1).subs) == 3
if isstr(subs{1}), subs{1} = [1:size(a,1)]; end;
if isstr(subs{2}), subs{2} = [1:size(a,2)]; end;
if ndims(a) == 2,
subs(3) = [];
else
if isstr(subs{3}), subs{3} = [1:size(a,3)]; end;
end;
finaldim = cellfun('length', subs);
end;
% non-transposed data
% -------------------
if ~strcmpi(a.fileformat, 'transposed')
if length(subs) == 1, b = a.data.data.x(subs{1}); end;
if length(subs) == 2, b = a.data.data.x(subs{1}, subs{2}); end;
if length(subs) == 3, b = a.data.data.x(subs{1}, subs{2}, subs{3}); end;
else
if ndims(a) == 2
%if length(s) == 0, b = transpose(a.data.data.x); return; end;
if length(s(1).subs) == 1, b = a.data.data.x(s(1).subs{1})'; end;
if length(s(1).subs) == 2, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end;
if length(s(1).subs) == 3, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end;
else
%if length(s) == 0, b = permute(a.data.data.x, [3 1 2]); return; end;
if length(subs) == 1,
inds1 = mod(subs{1}-1, size(a,1))+1;
inds2 = mod((subs{1}-inds1)/size(a,1), size(a,2))+1;
inds3 = ((subs{1}-inds1)/size(a,1)-inds2+1)/size(a,2)+1;
inds = (inds1-1)*size(a,2)*size(a,3) + (inds3-1)*size(a,2) + inds2;
b = a.data.data.x(inds);
else
if length(subs) < 2, subs{3} = 1; end;
% repmat if several indices in different dimensions
% -------------------------------------------------
len = cellfun('length', subs);
subs{1} = repmat(reshape(subs{1}, [len(1) 1 1]), [1 len(2) len(3)]);
subs{2} = repmat(reshape(subs{2}, [1 len(2) 1]), [len(1) 1 len(3)]);
subs{3} = repmat(reshape(subs{3}, [1 1 len(3)]), [len(1) len(2) 1]);
inds = (subs{1}-1)*a.data.Format{2}(1)*a.data.Format{2}(2) + (subs{3}-1)*a.data.Format{2}(1) + subs{2};
inds = reshape(inds, [1 prod(size(inds))]);
b = a.data.data.x(inds);
end;
end;
end;
if length(finaldim) == 1, finaldim(2) = 1; end;
b = reshape(b, finaldim);
% 2 dims
%inds1 = mod(myinds-1, size(a,1))+1;
%inds2 = (myinds-inds1)/size(a,1)+1;
%inds = (inds2-1)*size(a,1) + inds1;
% 3 dims
%inds1 = mod(myinds-1, size(a,1))+1;
%inds2 = mod((myinds-inds1)/size(a,1), size(a,2))+1;
%inds3 = ((myinds-inds1)/size(a,1)-inds2)/size(a,2)+1;
%inds = (inds3-1)*size(a,1)*size(a,2) + inds2*size(a,1) + inds1;
|
github
|
lcnbeapp/beapp-master
|
ndims.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/ndims.m
| 1,169 |
utf_8
|
8c3ed2dde450e1422a2552d22e9c150b
|
% ndims() - number of dimension of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function s = ndims(a)
if ~strcmpi(a.fileformat, 'transposed')
if a.data.Format{2}(3) == 1, s = 2;
else s = 3;
end;
else
if a.data.Format{2}(2) == 1, s = 2;
else s = 3;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
memmapdata.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@memmapdata/memmapdata.m
| 1,994 |
utf_8
|
5f967fcb7b637954900e09789144dde6
|
% memmapdata() - create a memory-mapped data class
%
% Usage:
% >> data_class = memmapdata(data);
%
% Inputs:
% data - input data or data file
%
% Outputs:
% data_class - output dataset class
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function dataout = memmapdata(data, datadims);
dataout.fileformat = 'normal';
if isstr(data)
if length(data) > 3
if strcmpi('.dat', data(end-3:end))
dataout.fileformat = 'transposed';
end;
end;
% check that the file is not empty
% --------------------------------
a = dir(data);
if isempty(a)
error([ 'Data file ''' data '''not found' ]);
elseif a(1).bytes == 0
error([ 'Empty data file ''' data '''' ]);
end;
if ~strcmpi(dataout.fileformat, 'transposed')
dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' datadims 'x' });
else
dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' [ datadims(2:end) datadims(1) ] 'x' });
end;
dataout = class(dataout,'memmapdata');
else
dataout = data;
end;
|
github
|
lcnbeapp/beapp-master
|
display.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/display.m
| 1,161 |
utf_8
|
b43db5e3387d5dcb39fafa9aa03939f9
|
% display() - display an EEG data class underlying structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function display(obj);
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
if obj.transposed, disp('Warning: data does not display properly for memory mapped file which have been transposed'); end;
disp(tmpMMO.data.x);
|
github
|
lcnbeapp/beapp-master
|
reshape.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/reshape.m
| 1,242 |
utf_8
|
cc03295fbaa6179eb2e8b266daf6b644
|
% reshape() - reshape of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function obj = reshape(obj,d1,d2,d3)
% decode length
% -------------
if nargin > 3
d1 = [ d1 d2 d3 ];
elseif nargin > 2
d1 = [ d1 d2 ];
end;
if prod(size(obj)) ~= prod(d1)
error('Wrong dimensions for reshaping');
end;
if obj.transposed
d1 = [d1(2:end) d1(1)];
end;
obj.dimensions = d1;
|
github
|
lcnbeapp/beapp-master
|
subsasgn_old.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/subsasgn_old.m
| 9,802 |
utf_8
|
0fc68a1bfa60e3118b3a4b6efd10fa52
|
% subsasgn() - define index assignment for eegdata objects
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function obj = subsasgn(obj,ss,val)
% check stack
% -----------
stack = dbstack;
stack(1) = [];
stack = rmfield(stack, 'line');
ncopies = 0;
if ~isempty(stack)
% check if we are in a different workspace
if ~isequal(stack, obj.workspace)
% if subfunction, must be a copie
if ~isempty(obj.workspace) && strcmpi(stack(end).file, obj.workspace(end).file) && ...
~strcmpi(stack(end).name, obj.workspace(end).name)
% We are within a subfunction. The MMO must have
% been passed as an argument (otherwise the current
% workspace and the workspace variable would be
% equal).
ncopies = 2;
else
tmpVar = evalin('caller', 'nargin;'); % this does not work
if ~isscript(stack(1).file)
ncopies = 2;
% we are within a function. The MMO must have
% been passed as an argument (otherwise the current
% workspace and the workspace variable would be
% equal).
else
% we cannot be in a function with 0 argument
% (otherwise the current workspace and the workspace
% variable would be equal). We must assume that
% we are in a script.
while ~isempty(stack) && ~isequal(stack, obj.workspace)
stack(1) = [];
end;
if ~isequal(stack, obj.workspace)
ncopies = 2;
end;
end;
end;
end;
end;
% check local variables
% ---------------------
if ncopies < 2
s = evalin('caller', 'whos');
for index = 1:length(s)
if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell')
tmpVar = evalin('caller', s(index).name);
ncopies = ncopies + checkcopies_local(obj, tmpVar);
elseif strcmpi(s(index).class, 'mmo')
if s(index).persistent || s(index).global
disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.');
end;
tmpVar = evalin('caller', s(index).name);
if isequal(tmpVar, obj), ncopies = ncopies + 1; end;
if ncopies > 1, break; end;
end;
end;
end;
% removing some entries
% ---------------------
if isempty(val)
newdim1 = obj.dimensions;
newdim2 = obj.dimensions;
% create new array of new size
% ----------------------------
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9));
% find non singleton dimension
% ----------------------------
nonSingleton = [];
for index = 1:length(subs)
if ~isstr(subs{index}) % can only be ":"
nonSingleton(end+1) = index;
subs2 = setdiff_bc([1:newdim1(index)], subs{index}); % invert selection
end;
end;
if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end;
if isempty(nonSingleton), obj = []; return; end;
% compute new final dimension
% ---------------------------
if length(ss(1).subs) == 1
fid = fopen(newFileName, 'w');
newdim2 = prod(newdim2)-length(ss(1).subs{1});
newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1});
for index = newindices
fwrite(fid, tmpMMO.Data.x(index), 'float');
end;
fclose(fid);
else
newdim2(nonSingleton) = newdim2(nonSingleton)-length(subs{index});
tmpdata = builtin('subsref', tmpMMO.Data.x, s);
fid = fopen(newFileName, 'w');
fwrite(fid, tmpMMO.Data.x(index), 'float');
fclose(fid);
end;
% delete file if necessary
if ncopies == 1 && obj.writable
delete(obj.dataFile);
end;
if obj.debug, disp('new copy created, old deleted (length 1)'); end;
obj.dimensions = [1 newdim2];
obj.dataFile = newFileName;
obj.writable = true;
clear tmpMMO;
return;
elseif ncopies == 1 && obj.writable
for index = 1:length(ss(1).subs)
newdim2(notOneDim) = newdim2(notOneDim)-length(ss(1).subs{1});
if index > length(newdim2)
newdim2(index) = max(ss(1).subs{index});
else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index));
end;
end;
% create new array of new size
% -----------------------------------------
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9));
% copy file row by row
% --------------------
fid = fopen(newFileName, 'w');
tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single');
for index = 1:prod(newdim1(2:end))
fwrite(fid, tmpMMO.Data.x(:,index), 'float');
fwrite(fid, tmpdata, 'float');
end;
if prod(newadim1(2:end)) ~= prod(newdim2(2:end))
tmpdata = zeros(newdim2(1), 1, 'single');
for index = prod(newdim1(2:end))+1:prod(newdim2(2:end))
fwrite(fid, tmpdata, 'float');
end;
end;
fclose(fid);
% delete file if necessary
if ncopies == 1 && obj.writable
delete(obj.dataFile);
end;
if obj.debug, disp('new copy created, old deleted'); end;
obj.dimensions = newdim2;
obj.dataFile = newFileName;
obj.writable = true;
clear tmpMMO;
else
% check size
% ----------
newdim1 = obj.dimensions;
newdim2 = obj.dimensions;
if length(ss(1).subs) == 1
if max(ss(1).subs{1}) > prod(newdim2)
notOneDim = find(newdim2 > 1);
if length(notOneDim) == 1
newdim2(notOneDim) = max(ss(1).subs{1});
end;
end;
else
for index = 1:length(ss(1).subs)
if index > length(newdim2)
newdim2(index) = max(ss(1).subs{index});
else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index));
end;
end;
end;
% create new array of new size if necessary
% -----------------------------------------
if ~isequal(newdim1, newdim2)
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9));
% copy file row by row
% --------------------
fid = fopen(newFileName, 'w');
tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single');
for index = 1:prod(newdim1(2:end))
fwrite(fid, tmpMMO.Data.x(:,index), 'float');
fwrite(fid, tmpdata, 'float');
end;
if prod(newdim1(2:end)) ~= prod(newdim2(2:end))
tmpdata = zeros(newdim2(1), 1, 'single');
for index = prod(newdim1(2:end))+1:prod(newdim2(2:end))
fwrite(fid, tmpdata, 'float');
end;
end;
fclose(fid);
% delete file if necessary
if ncopies == 1 && obj.writable
delete(obj.dataFile);
end;
if obj.debug, disp('new copy created, old deleted'); end;
obj.dimensions = newdim2;
obj.dataFile = newFileName;
obj.writable = true;
clear tmpMMO;
% create copy if necessary
% ------------------------
elseif ncopies > 1 || ~obj.writable
newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9));
copyfile(obj.dataFile, newFileName);
obj.dataFile = newFileName;
obj.writable = true;
if obj.debug, disp('new copy created'); end;
else
if obj.debug, disp('using same copy'); end;
end;
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val);
end;
return;
% i.type = '()';
% i.subs = { ':' ':' ':' };
% res = subsref(obj, i); % note that subsref cannot be called directly
% subfunction checking the number of copies
% -----------------------------------------
function ncopies = checkcopies_local(obj, arg);
ncopies = 0;
if isstruct(arg)
for ilen = 1:length(arg)
for index = fieldnames(arg)'
ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1}));
if ncopies > 1, return; end;
end;
end;
elseif iscell(arg)
for index = 1:length(arg(:))
ncopies = ncopies + checkcopies_local(obj, arg{index});
if ncopies > 1, return; end;
end;
elseif isa(arg, 'mmo') && isequal(obj, arg)
ncopies = 1;
else
ncopies = 0;
end;
|
github
|
lcnbeapp/beapp-master
|
end.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/end.m
| 901 |
utf_8
|
0e38d125a547083cb574fbd3bb455fbd
|
% end() - last index to memmapdata array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function s = end(a, k, n);
s = size(a, k);
|
github
|
lcnbeapp/beapp-master
|
subsasgn.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/subsasgn.m
| 10,655 |
utf_8
|
c4514f5b1f0fec385eeb19fee7a5db56
|
% subsasgn() - define index assignment for eegdata objects
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function obj = subsasgn(obj,ss,val)
% check empty assignement
% -----------------------
for index = 1:length(ss(1).subs)
if isempty(ss(1).subs{index}), return; end;
end;
% remove useless ":"
% ------------------
while length(obj.dimensions) < length(ss(1).subs)
if isequal(ss(1).subs{end}, ':')
ss(1).subs(end) = [];
else
break;
end;
end;
% deal with transposed data
% -------------------------
if obj.transposed, ss = transposeindices(obj, ss); end;
% check stack and local variables
% ---------------------
ncopies = checkworkspace(obj);
if ncopies < 2
if isempty(inputname(1))
vers = version;
indp = find(vers == '.');
if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end;
indp = find(vers == '.');
vers = str2num(vers(1:indp(2)-1));
if vers >= 7.13
% the problem with Matlab 2012a/2011b is that if the object called is
% in a field of a structure (empty inputname), the evaluation
% in the caller of the object variable is empty in 2012a. A bug
% repport has been submitted to Matlab - Arno
ncopies = ncopies + 1;
end;
end;
s = evalin('caller', 'whos');
for index = 1:length(s)
if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell')
tmpVar = evalin('caller', s(index).name);
ncopies = ncopies + checkcopies_local(obj, tmpVar);
elseif strcmpi(s(index).class, 'mmo')
if s(index).persistent || s(index).global
disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.');
end;
tmpVar = evalin('caller', s(index).name);
if isequal(tmpVar, obj), ncopies = ncopies + 1; end;
if ncopies > 1, break; end;
end;
end;
end;
% removing some entries
% ---------------------
if isempty(val)
newdim1 = obj.dimensions;
newdim2 = obj.dimensions;
% create new array of new size
% ----------------------------
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
newFileName = mmo.getnewfilename;
% find non singleton dimension
% ----------------------------
nonSingleton = [];
ss2 = ss;
for index = 1:length(ss(1).subs)
if ~isstr(ss(1).subs{index}) % can only be ":"
nonSingleton(end+1) = index;
ss2(1).subs{index} = setdiff_bc([1:newdim1(index)], ss(1).subs{index}); % invert selection
end;
end;
if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end;
if isempty(nonSingleton), obj = []; return; end;
% compute new final dimension and copy data
% -----------------------------------------
if length(ss(1).subs) == 1
fid = fopen(newFileName, 'w');
newdim2 = [ prod(newdim2)-length(ss(1).subs{1}) ];
if ~(newdim1(1) > 1 && all(newdim1(2:end) == 1)), newdim2 = [1 newdim2];
else newdim2 = [newdim2 1]; end;
newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1});
for index = newindices
fwrite(fid, tmpMMO.Data.x(index), 'float');
end;
fclose(fid);
fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive');
else
if length(ss(1).subs) < length(newdim2)
newdim2(length(ss(1).subs)) = prod(newdim2(length(ss(1).subs):end));
newdim2(length(ss(1).subs)+1:end) = [];
if nonSingleton == length(ss(1).subs)
ss2(1).subs{end} = setdiff_bc([1:newdim2(end)], ss(1).subs{end});
end;
end;
newdim2(nonSingleton) = newdim2(nonSingleton)-length(ss(1).subs{nonSingleton});
if isstr(ss2.subs{end})
ss2.subs{end} = [1:prod(newdim1(length(ss2.subs):end))];
end;
ss3 = ss2;
fid = fopen(newFileName, 'w');
% copy large blocks
alllen = cellfun(@length, ss2.subs);
inc = ceil(250000/prod(alllen(1:end-1))); % 1Mb block
for index = 1:inc:length(ss2.subs{end})
ss3.subs{end} = ss2.subs{end}(index:min(index+inc, length(ss2.subs{end})));
tmpdata = subsref(tmpMMO.Data.x, ss3);
fwrite(fid, tmpdata, 'float');
end;
fclose(fid);
fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive');
end;
% delete file if necessary
if ncopies == 1 && obj.writable
delete(obj.dataFile);
end;
if obj.debug, disp('new copy created, old deleted (length 1)'); end;
obj.dimensions = newdim2;
obj.dataFile = newFileName;
obj.writable = true;
obj = updateWorkspace(obj);
clear tmpMMO;
return;
else
% check size to see if it increases
% ---------------------------------
newdim1 = obj.dimensions;
newdim2 = newdim1;
if length(ss(1).subs) == 1
if ~isstr(ss(1).subs{1}) && max(ss(1).subs{1}) > prod(newdim1)
if length(newdim1) > 2
error('Attempt to grow array along ambiguous dimension.');
end;
end;
if max(ss(1).subs{1}) > prod(newdim2)
notOneDim = find(newdim2 > 1);
if length(notOneDim) == 1
newdim2(notOneDim) = max(ss(1).subs{1});
end;
end;
else
if length(newdim1) == 3 && newdim1(3) == 1, newdim1(end) = []; end;
if length(ss(1).subs) == 2 && length(newdim1) == 3
if ~isstr(ss(1).subs{2}) && max(ss(1).subs{2}) > prod(newdim1(2:end))
error('Attempt to grow array along ambiguous dimension.');
end;
if isnumeric(ss(1).subs{1}), newdim2(1) = max(max(ss(1).subs{1}), newdim2(1)); end;
else
for index = 1:length(ss(1).subs)
if isnumeric(ss(1).subs{index})
if index > length(newdim2)
newdim2(index) = max(ss(1).subs{index});
else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index));
end;
end;
end;
end;
end;
% create new array of new size if necessary
% -----------------------------------------
if ~isequal(newdim1, newdim2)
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
newFileName = mmo.getnewfilename;
% copy file row by row
% --------------------
fid = fopen(newFileName, 'w');
dim1 = [ newdim1 1 1 1 1 ];
dim2 = [ newdim2 1 1 1 1 ];
tmpdata1 = zeros(prod(dim2(1:1)) - prod(dim1(1:1)), 1, 'single');
tmpdata2 = zeros((dim2(2) - dim1(2))*dim2(1), 1, 'single');
tmpdata3 = zeros((dim2(3) - dim1(3))*prod(dim2(1:2)), 1, 'single');
% copy new data (copy first array)
% -------------
for index3 = 1:dim1(3)
if dim1(1) == dim2(1) && dim1(2) == dim2(2)
fwrite(fid, tmpMMO.Data.x(:,:,index3), 'float');
else
for index2 = 1:dim1(2)
if dim1(1) == dim2(1)
fwrite(fid, tmpMMO.Data.x(:,index2,index3), 'float');
else
for index1 = 1:dim1(1)
fwrite(fid, tmpMMO.Data.x(index1,index2,index3), 'float');
end;
end;
fwrite(fid, tmpdata1, 'float');
end;
end;
fwrite(fid, tmpdata2, 'float');
end;
fwrite(fid, tmpdata3, 'float');
fclose(fid);
fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive');
% delete file if necessary
if ncopies == 1 && obj.writable
delete(obj.dataFile);
end;
if obj.debug, disp('new copy created, old deleted'); end;
obj.dimensions = newdim2;
obj.dataFile = newFileName;
obj.writable = true;
clear tmpMMO;
% create copy if necessary
% ------------------------
elseif ncopies > 1 || ~obj.writable
newFileName = mmo.getnewfilename;
copyfile(obj.dataFile, newFileName);
obj.dataFile = newFileName;
obj.writable = true;
if obj.debug, disp('new copy created'); end;
else
if obj.debug, disp('using same copy'); end;
end;
% copy new data
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
if ~isa(val, 'mmo')
tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val);
else
% copy memory mapped array
if ndims(val) == 2 && (size(val,1) == 1 || size(val,2) == 1)
% vector direct copy
ss2.type = '()';
ss2.subs = { ':' ':' ':' };
tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, subsref(val,ss2));
else
ss2.type = '()';
ss2.subs = { ':' ':' ':' };
ss3 = ss;
% array, copy each channel
for index1 = 1:size(val,1)
ss2(1).subs{1} = index1;
if isstr(ss(1).subs{1}) ss3(1).subs{1} = index1;
else ss3(1).subs{1} = ss(1).subs{1}(index1);
end;
tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss3, subsref(val,ss2));
end;
end;
end;
obj = updateWorkspace(obj);
end;
|
github
|
lcnbeapp/beapp-master
|
isnumeric.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/isnumeric.m
| 877 |
utf_8
|
34baf204e1b984ee69cf7f462fe2e524
|
% isnumeric() - returns 1
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function r = isnumeric(a)
r = 1;
|
github
|
lcnbeapp/beapp-master
|
checkcopies_local.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/checkcopies_local.m
| 634 |
utf_8
|
8eb8d5fec95c91346e91a09010082b47
|
% subfunction checking the number of local copies
% -----------------------------------------------
function ncopies = checkcopies_local(obj, arg);
ncopies = 0;
if isstruct(arg)
for ilen = 1:length(arg)
for index = fieldnames(arg)'
ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1}));
if ncopies > 1, return; end;
end;
end;
elseif iscell(arg)
for index = 1:length(arg(:))
ncopies = ncopies + checkcopies_local(obj, arg{index});
if ncopies > 1, return; end;
end;
elseif isa(arg, 'mmo') && isequal(obj, arg)
ncopies = 1;
else
ncopies = 0;
end;
|
github
|
lcnbeapp/beapp-master
|
changefile.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/changefile.m
| 187 |
utf_8
|
e75127c90da43ddce182d36cf0abbdee
|
% this function is called when the file is being saved
function obj = changefile(obj, newfile)
movefile(obj.dataFile, newfile);
obj.dataFile = newfile;
obj.writable = false;
|
github
|
lcnbeapp/beapp-master
|
var.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/var.m
| 1,416 |
utf_8
|
2360192fa42b3c35ebd7743ffe4fe8b6
|
% var() - variance of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function sumval = var(obj,flag,dim)
if nargin < 2
flag = 0;
end;
if nargin < 3
dim = 1;
end;
meanvalsq = mean(obj,dim).^2;
sumval = 0;
s1 = size(obj);
ss.type = '()';
ss.subs(1:length(s1)) = { ':' };
for index = 1:s1(dim)
ss.subs{dim} = index;
tmpdata = subsref(obj, ss);
sumval = sumval + tmpdata.*tmpdata - meanvalsq;
end;
if isempty(flag) || flag == 0
sumval = sumval/(size(obj,dim)-1);
else sumval = sumval/size(obj,dim);
end;
|
github
|
lcnbeapp/beapp-master
|
length.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/length.m
| 913 |
utf_8
|
f0841237745a123f3215e00164cc4a1a
|
% length() - length of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function s = length(a)
s = size(a,1);
|
github
|
lcnbeapp/beapp-master
|
sum.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/sum.m
| 1,212 |
utf_8
|
2fbce1d1b6e2a5edf32742897441a732
|
% sum() - sum of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function sumval = sum(obj,dim)
if nargin < 2
dim = 1;
end;
s1 = size(obj);
ss.type = '()';
ss.subs(1:length(s1)) = { ':' };
for index = 1:s1(dim)
ss.subs{dim} = index;
if index == 1
sumval = subsref(obj, ss);
else sumval = sumval + subsref(obj, ss);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
size.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/size.m
| 1,751 |
utf_8
|
daf6932de04161ccb2df3df31b45203a
|
% size() - size of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [s varargout] = size(obj,dim)
if obj.transposed
if length(obj.dimensions) ~= 2 && length(obj.dimensions) ~= 3
error('Transposed array must be 2 or 3 dims');
end;
if length(obj.dimensions) == 2 tmpdimensions = [obj.dimensions(2) obj.dimensions(1)];
else tmpdimensions = [obj.dimensions(3) obj.dimensions(1:end-1)];
end;
else
tmpdimensions = obj.dimensions;
end;
s = tmpdimensions;
if nargin > 1
if dim >length(s)
s = 1;
else
s = s(dim);
end;
else
if nargout > 1
s = [s 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1];
alls = s;
s = s(1);
for index = 1:max(nargout,1)-1
varargout{index} = alls(index+1);
end;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
subsref.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/subsref.m
| 2,711 |
utf_8
|
1da2db6dbbc53f36d6d2954f095f9064
|
% subsref() - index eegdata class
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function res = subsref(obj,s)
if strcmpi(s(1).type, '.')
res = builtin('subsref', obj, s);
return;
end;
tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });
subs = s(1).subs;
finaldim = cellfun('length', subs);
% one dimension input
% -------------------
if length(s) > 1 || ~strcmpi(s(1).type, '()')
error('MMO can only map single array data files');
end;
% deal with transposed data
% -------------------------
if obj.transposed, s = transposeindices(obj, s); end;
% convert : to real sizes
% -----------------------
lastdim = length(subs);
if isstr(subs{end}) && ndims(obj) > lastdim
for index = lastdim+1:ndims(obj)
if index > length(obj.dimensions)
subs{index} = 1;
else
subs{index} = [1:obj.dimensions(index)];
end;
end;
end;
for index = 1:length(subs)
if isstr(subs{index}) % can only be ":"
if index > length(obj.dimensions)
subs{index} = 1;
else
subs{index} = [1:obj.dimensions(index)];
end;
end;
end;
finaldim = cellfun(@length, subs);
finaldim(lastdim) = prod(finaldim(lastdim:end));
finaldim(lastdim+1:end) = [];
% non-transposed data
% -------------------
res = tmpMMO.data.x(subs{:});
if length(finaldim) == 1, finaldim(2) = 1; end;
res = reshape(res, finaldim);
if obj.transposed
if finaldim(end) == 1, finaldim(end) = []; end;
if length(finaldim) <= 2, res = res';
else
res = reshape(res, [finaldim(1)*finaldim(2) finaldim(3)])';
res = reshape(res, [finaldim(3) finaldim(1) finaldim(2)]);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
ndims.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/@mmo/ndims.m
| 1,095 |
utf_8
|
7ddcbafa2aaf95308a1a4de4a272f0ae
|
% ndims() - number of dimension of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function res = ndims(obj)
if length(obj.dimensions) <= 2 || all(obj.dimensions(3:end) == 1), res = 2;
else res = length(obj.dimensions);
end;
|
github
|
lcnbeapp/beapp-master
|
correctfit.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/correctfit.m
| 3,222 |
utf_8
|
69c8b2f965023329820bdfd3c7e82176
|
% correctfit() - correct fit using observed p-values. Use this function
% if for some reason, the distribution of p values is
% not uniform between 0 and 1
%
% Usage:
% >> [p phat pci zerofreq] = correctfit(pval, 'key', 'val');
%
% Inputs:
% pval - input p value
%
% Optional inputs:
% 'allpval' - [float array] collection of p values drawn from random
% distributions (theoritically uniform).
% 'gamparams' - [phat pci zerofreq] parameter for gamma function fitting.
% zerofreq is the frequency of occurence of p=0.
% 'zeromode' - ['on'|'off'] enable estimation of frequency of pval=0
% (this might lead to hight pval). Default is 'on'.
%
% Outputs:
% p - corrected p value.
% phat - phat gamfit() parameter.
% pci - phat gamfit() parameter.
% zerofreq - frequency of occurence of p=0.
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2003-
%
% See also: bootstat()
% Copyright (C) 7/02/03 Arnaud Delorme, SCCN/INC/UCSD
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [pval, PHAT, PCI, zerofreq] = correctfit(pval, varargin)
if nargin < 2
help correctfit;
disp('You need to specify one optional input');
return;
end;
g = finputcheck( varargin, { 'allpval' 'real' [0 1] [];
'zeromode' 'string' {'on','off'} 'on';
'gamparams' 'real' [] []}, 'correctfit');
if isstr(g), error(g); end;
if ~isempty(g.gamparams)
PHAT = g.gamparams(1);
PCI = g.gamparams(2);
zerofreq = g.gamparams(3);
elseif ~isempty(g.allpval)
nonzero = find(g.allpval(:) ~= 0);
zerofreq = (length(g.allpval(:))-length(nonzero))/ length(g.allpval(:));
tmpdat = -log10( g.allpval(nonzero) ) + 1E-10;
[PHAT, PCI] = gamfit( tmpdat );
PHAT = PHAT(1);
PCI = PCI(2);
end;
if pval == 0
if strcmpi(g.zeromode, 'on')
pval = zerofreq;
end;
else
tmppval = -log10( pval ) + 1E-10;
pval = 1-gamcdf( tmppval, PHAT, PCI);
end;
if 1 % plotting
if exist('tmpdat') == 1
figure; hist(tmpdat, 100); hold on;
mult = ylim;
tmpdat = linspace(0.00001,10, 300);
normy = gampdf( tmpdat, PHAT, PCI);
plot( tmpdat, normy/max(normy)*mult(2)*3, 'r');
end;
end;
|
github
|
lcnbeapp/beapp-master
|
timef.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/timef.m
| 42,818 |
utf_8
|
6663467d76d01722baccf168fec18e1b
|
% timef() - Returns estimates and plots of mean event-related spectral
% perturbation (ERSP) and inter-trial coherence (ITC) changes
% across event-related trials (epochs) of a single input time series.
% * Uses either fixed-window, zero-padded FFTs (fastest), wavelet
% 0-padded DFTs (both Hanning-tapered), OR multitaper spectra ('mtaper').
% * For the wavelet and FFT methods, output frequency spacing
% is the lowest frequency ('srate'/'winsize') divided by 'padratio'.
% NaN input values (such as returned by eventlock()) are ignored.
% * If 'alpha' is given, then bootstrap statistics are computed
% (from a distribution of 'naccu' surrogate data trials) and
% non-significant features of the output plots are zeroed out
% (i.e., plotted in green).
% * Given a 'topovec' scalp map weights vector and an 'elocs' electrode
% location file or structure, the figure also shows a topoplot()
% image of the specified scalp map.
%
% * Note: Left-click on subplots to view and zoom in separate windows.
% Usage:
% >> [ersp,itc,powbase,times,freqs,erspboot,itcboot,itcphase] = ...
% timef(data,frames,tlimits,srate,cycles,...
% 'key1',value1,'key2',value2, ... );
% NOTE:
% * For more detailed information about timef(), >> timef details
% * Default values may differ when called from pop_timef()
%
% Required inputs:
% data = Single-channel data vector (1,frames*ntrials) (required)
% frames = Frames per trial {def|[]: datalength}
% tlimits = [mintime maxtime] (ms) Epoch time limits
% {def|[]: from frames,srate}
% srate = data sampling rate (Hz) {def:250}
% cycles = If 0 -> Use FFTs (with constant window length) {0 = FFT}
% If >0 -> Number of cycles in each analysis wavelet
% If [wavecycles factor] -> wavelet cycles increase with
% frequency beginning at wavecyles (0<factor<1; factor=1
% -> no increase, standard wavelets; factor=0 -> fixed epoch
% length, as in FFT. Else, 'mtaper' -> multitaper decomp.
%
% Optional Inter-Irial Coherence (ITC) type:
% 'type' = ['coher'|'phasecoher'] Compute either linear coherence
% ('coher') or phase coherence ('phasecoher') also known
% as the phase coupling factor {'phasecoher'}.
% Optional detrending:
% 'detret' = ['on'|'off'], Detrend data in time. {'off'}
% 'detrep' = ['on'|'off'], Detrend data across trials {'off'}
%
% Optional FFT/DFT parameters:
% 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames);
% If cycles >0: *longest* window length to use. This
% determines the lowest output frequency {~frames/8}
% 'timesout' = Number of output times (int<frames-winframes) {200}
% 'padratio' = FFT-length/winframes (2^k) {2}
% Multiplies the number of output frequencies by
% dividing their spacing. When cycles==0, frequency
% spacing is (low_freq/padratio).
% 'maxfreq' = Maximum frequency (Hz) to plot (& to output if cycles>0)
% If cycles==0, all FFT frequencies are output. {50}
% 'baseline' = Spectral baseline window center end-time (in ms). {0}
% 'powbase' = Baseline spectrum (power, not dB) to normalize the data.
% {def|NaN->from data}
%
% Optional multitaper parameters:
% 'mtaper' = If [N W], performs multitaper decomposition.
% (N is the time resolution and W the frequency resolution;
% maximum taper number is 2NW-1). Overwrites 'winsize' and
% 'padratio'.
% If [N W K], uses K Slepian tapers (if possible).
% Phase is calculated using standard methods.
% The use of mutitaper with wavelets (cycles>0) is not
% recommended (as multiwavelets are not implemented).
% Uses Matlab functions DPSS, PMTM. {no multitaper}
%
% Optional bootstrap parameters:
% 'alpha' = If non-0, compute two-tailed bootstrap significance prob.
% level. Show non-signif. output values in green {0}
% 'naccu' = Number of bootstrap replications to accumulate {200}
% 'baseboot' = Bootstrap baseline to subtract (1 -> use 'baseline'(above)
% 0 -> use whole trial) {1}
% Optional scalp map:
% 'topovec' = Scalp topography (map) to plot {none}
% 'elocs' = Electrode location file for scalp map
% File should be ascii in format of >> topoplot example
% May also be an EEG.chanlocs struct.
% {default: file named in icadefs.m}
% Optional plotting parameters:
% 'hzdir' = ['up'|'down'] Direction of the frequency axes; reads default
% from icadefs.m {'up'}
% 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'}
% 'plotitc' = ['on'|'off'] Plot inter trial coherence {'on'}
% 'plotphase' = ['on'|'off'] Plot sign of the phase in the ITC panel, i.e.
% green->red, pos.-phase ITC, green->blue, neg.-phase ITC {'on'}
% 'erspmax' = [real dB] set the ERSP max. for the scale (min= -max){auto}
% 'itcmax' = [real<=1] set the ITC maximum for the scale {auto}
% 'title' = Optional figure title {none}
% 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none}
% 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2}
% 'pboot' = Bootstrap power limits (e.g., from timef()) {from data}
% 'rboot' = Bootstrap ITC limits (e.g., from timef()) {from data}
% 'axesfont' = Axes text font size {10}
% 'titlefont' = Title text font size {8}
% 'vert' = [times_vector] -> plot vertical dashed lines at given ms.
% 'verbose' = ['on'|'off'] print text {'on'}
%
% Outputs:
% ersp = Matrix (nfreqs,timesout) of log spectral diffs. from
% baseline (in dB). NB: Not masked for significance.
% Must do this using erspboot
% itc = Matrix of inter-trial coherencies (nfreqs,timesout)
% (range: [0 1]) NB: Not masked for significance.
% Must do this using itcboot
% powbase = Baseline power spectrum (NOT in dB, used to norm. the ERSP)
% times = Vector of output times (sub-window centers) (in ms)
% freqs = Vector of frequency bin centers (in Hz)
% erspboot = Matrix (2,nfreqs) of [lower;upper] ERSP significance diffs
% itcboot = Matrix (2,nfreqs) of [lower;upper] ITC thresholds (not diffs)
% itcphase = Matrix (nfreqs,timesout) of ITC phase (in radians)
%
% Plot description:
% Assuming both 'plotersp' and 'plotitc' options are 'on' (= default).
% The upper panel presents the data ERSP (Event-Related Spectral Perturbation)
% in dB, with mean baseline spectral activity (in dB) subtracted. Use
% "'baseline', NaN" to prevent timef() from removing the baseline.
% The lower panel presents the data ITC (Inter-Trial Coherence).
% Click on any plot axes to pop up a new window (using 'axcopy()')
% -- Upper left marginal panel presents the mean spectrum during the baseline
% period (blue), and when significance is set, the significance threshold
% at each frequency (dotted green-black trace).
% -- The marginal panel under the ERSP image shows the maximum (green) and
% minimum (blue) ERSP values relative to baseline power at each frequency.
% -- The lower left marginal panel shows mean ITC across the imaged time range
% (blue), and when significance is set, the significance threshold (dotted
% green-black).
% -- The marginal panel under the ITC image shows the ERP (which is produced by
% ITC across the data spectral pass band).
%
% Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig
% CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002-
%
% Known problems:
% Significance masking currently fails for linear coherence.
%
% See also: crossf()
% Copyright (C) 1998 Sigurd Enghoff, Scott Makeig, Arnaud Delorme,
% CNL / Salk Institute 8/1/98-8/28/01
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 10-19-98 avoided division by zero (using MIN_ABS) -sm
% 10-19-98 improved usage message and commandline info printing -sm
% 10-19-98 made valid [] values for tvec and g.elocs -sm
% 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se & -tpj
% 06-29-99 fixed frequency indexing for constant-Q -se
% 08-24-99 reworked to handle NaN input values -sm
% 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm
% 12-22-99 debugged ERPtimes, added BASE_BOOT -sm
% 01-10-00 debugged BASE_BOOT=0 -sm
% 02-28-00 added NOTE on formula derivation below -sm
% 03-16-00 added axcopy() feature -sm & tpj
% 04-16-00 added multiple marktimes loop -sm
% 04-20-00 fixed ITC cbar limits when spcified in input -sm
% 07-29-00 changed frequencies displayed msg -sm
% 10-12-00 fixed bug in freqs when cycles>0 -sm
% 02-07-01 fixed inconsistency in BASE_BOOT use -sm
% 08-28-01 matlab 'key' value arguments -ad
% 08-28-01 multitaper decomposition -ad
% 01-25-02 reformated help & license -ad
% 03-08-02 debug & compare to old timef function -ad
% 03-16-02 timeout automatically adjusted if too high -ad
% 04-02-02 added 'coher' option -ad
function [P,R,mbase,times,freqs,Pboot,Rboot,Rphase,PA] = timef(X,frames,tlimits,Fs,varwin,varargin);
% Note: undocumented arg PA is output of 'phsamp','on'
%varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot)
% ITC: Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is linear coherence.
% But here, we consider: Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx
% Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC)
% Also called 'phase-locking factor' by Tallon-Baudry et al. (1996),
% the ITC is the phase coherence between the data time series and the
% time-locking event time series.
% Read system-wide / dir-wide constants:
icadefs
% Constants set here:
ERSP_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value
% giving symmetric +/- caxis limits.
ITC_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value
% giving symmetric +/- caxis limits.
% Commandline arg defaults:
DEFAULT_EPOCH = NaN; % Frames per trial
DEFAULT_TIMLIM = NaN; % Time range of g.frames (ms)
DEFAULT_FS = 250; % Sampling frequency (Hz)
DEFAULT_NWIN = 200; % Number of windows = horizontal resolution
DEFAULT_VARWIN = 0; % Fixed window length or fixed number of cycles.
% =0: fix window length to that determined by nwin
% >0: set window length equal to varwin cycles
% Bounded above by winsize, which determines
% the min. freq. to be computed.
DEFAULT_OVERSMP = 2; % Number of times to oversample frequencies
DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz)
DEFAULT_TITLE = ''; % Figure title
DEFAULT_ELOC = 'chan.locs'; % Channel location file
DEFAULT_ALPHA = NaN; % Percentile of bins to keep
DEFAULT_MARKTIME= NaN;
% Font sizes:
AXES_FONT = 10; % axes text FontSize
TITLE_FONT = 8;
if nargout>7
Rphase = []; % initialize in case Rphase asked for, but ITC not computed
end
if (nargin < 1)
help timef
return
end
if isstr(X) & strcmp(X,'details')
more on
help timefdetails
more off
return
end
if (min(size(X))~=1 | length(X)<2)
error('Data must be a row or column vector.');
end
if nargin < 2 | isempty(frames) | isnan(frames)
frames = DEFAULT_EPOCH;
elseif (~isnumeric(frames) | length(frames)~=1 | frames~=round(frames))
error('Value of frames must be an integer.');
elseif (frames <= 0)
error('Value of frames must be positive.');
elseif (rem(length(X),frames) ~= 0)
error('Length of data vector must be divisible by frames.');
end
if isnan(frames) | isempty(frames)
frames = length(X);
end
if nargin < 3 | isnan(tlimits) | isempty(tlimits)
tlimits = DEFAULT_TIMLIM;
elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3)
error('Value of tlimits must be a vector containing two numbers.');
elseif (tlimits(1) >= tlimits(2))
error('tlimits interval must be ascending.');
end
if (nargin < 4)
Fs = DEFAULT_FS;
elseif (~isnumeric(Fs) | length(Fs)~=1)
error('Value of srate must be a number.');
elseif (Fs <= 0)
error('Value of srate must be positive.');
end
if isnan(tlimits) | isempty(tlimits)
hlim = 1000*frames/Fs; % fit default tlimits to srate and frames
tlimits = [0 hlim];
end
framesdiff = frames - Fs*(tlimits(2)-tlimits(1))/1000;
if abs(framesdiff) > 1
error('Given time limits, frames and sampling rate are incompatible');
elseif framesdiff ~= 0
tlimits(1) = tlimits(1) - 0.5*framesdiff*1000/Fs;
tlimits(2) = tlimits(2) + 0.5*framesdiff*1000/Fs;
fprintf('Adjusted time limits slightly, to [%.1f,%.1f] ms, to match frames and srate.\n',tlimits(1),tlimits(2));
end
if (nargin < 5)
varwin = DEFAULT_VARWIN;
elseif (~isnumeric(varwin) | length(varwin)>2)
error('Value of cycles must be a number.');
elseif (varwin < 0)
error('Value of cycles must be zero or positive.');
end
% consider structure for these arguments
% --------------------------------------
if ~isempty(varargin)
try, g = struct(varargin{:});
catch, error('Argument error in the {''param'', value} sequence'); end;
end;
g.tlimits = tlimits;
g.frames = frames;
g.srate = Fs;
g.cycles = varwin(1);
if length(varwin)>1
g.cyclesfact = varwin(2);
else
g.cyclesfact = 1;
end;
try, g.title; catch, g.title = DEFAULT_TITLE; end;
try, g.winsize; catch, g.winsize = max(pow2(nextpow2(g.frames)-3),4); end;
try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end;
try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end;
try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end;
try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end;
try, g.topovec; catch, g.topovec = []; end;
try, g.elocs; catch, g.elocs = DEFAULT_ELOC; end;
try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end;
try, g.marktimes; catch, g.marktimes = DEFAULT_MARKTIME; end;
try, g.powbase; catch, g.powbase = NaN; end;
try, g.pboot; catch, g.pboot = NaN; end;
try, g.rboot; catch, g.rboot = NaN; end;
try, g.plotersp; catch, g.plotersp = 'on'; end;
try, g.plotitc; catch, g.plotitc = 'on'; end;
try, g.detrep; catch, g.detrep = 'off'; end;
try, g.detret; catch, g.detret = 'off'; end;
try, g.baseline; catch, g.baseline = 0; end;
try, g.baseboot; catch, g.baseboot = 1; end;
try, g.linewidth; catch, g.linewidth = 2; end;
try, g.naccu; catch, g.naccu = 200; end;
try, g.mtaper; catch, g.mtaper = []; end;
try, g.vert; catch, g.vert = []; end;
try, g.type; catch, g.type = 'phasecoher'; end;
try, g.phsamp; catch, g.phsamp = 'off'; end;
try, g.plotphase; catch, g.plotphase = 'on'; end;
try, g.itcmax; catch, g.itcmax = []; end;
try, g.erspmax; catch, g.erspmax = []; end;
try, g.verbose; catch, g.verbose = 'on'; end;
try, g.chaninfo; catch, g.chaninfo = []; end;
try, g.hzdir; catch, g.hzdir = HZDIR; end; % default from icadefs
lasterr('');
% testing arguments consistency
% -----------------------------
if strcmp(g.hzdir,'up')
g.hzdir = 'normal';
elseif strcmp(g.hzdir,'down')
g.hzdir = 'reverse';
else
error('unknown ''hzdir'' value - not ''up'' or ''down''');
end
switch lower(g.verbose)
case { 'on', 'off' }, ;
otherwise error('verbose must be either on or off');
end;
if (~ischar(g.title))
error('Title must be a string.');
end
if (~isnumeric(g.winsize) | length(g.winsize)~=1 | g.winsize~=round(g.winsize))
error('Value of winsize must be an integer number.');
elseif (g.winsize <= 0)
error('Value of winsize must be positive.');
elseif (g.cycles == 0 & pow2(nextpow2(g.winsize)) ~= g.winsize)
error('Value of winsize must be an integer power of two [1,2,4,8,16,...]');
elseif (g.winsize > g.frames)
error('Value of winsize must be less than frames per epoch.');
end
if (~isnumeric(g.timesout) | length(g.timesout)~=1 | g.timesout~=round(g.timesout))
error('Value of timesout must be an integer number.');
elseif (g.timesout <= 0)
error('Value of timesout must be positive.');
end
if (g.timesout > g.frames-g.winsize)
g.timesout = g.frames-g.winsize;
disp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]);
end
if (~isnumeric(g.padratio) | length(g.padratio)~=1 | g.padratio~=round(g.padratio))
error('Value of padratio must be an integer.');
elseif (g.padratio <= 0)
error('Value of padratio must be positive.');
elseif (pow2(nextpow2(g.padratio)) ~= g.padratio)
error('Value of padratio must be an integer power of two [1,2,4,8,16,...]');
end
if (~isnumeric(g.maxfreq) | length(g.maxfreq)~=1)
error('Value of maxfreq must be a number.');
elseif (g.maxfreq <= 0)
error('Value of maxfreq must be positive.');
elseif (g.maxfreq > Fs/2)
myprintf(g.verbose,['Warning: value of maxfreq reduced to Nyquist rate' ...
' (%3.2f)\n\n'], Fs/2);
g.maxfreq = Fs/2;
end
if isempty(g.topovec)
g.topovec = [];
if isempty(g.elocs)
error('Channel location file must be specified.');
end;
end
if isempty(g.elocs)
g.elocs = DEFAULT_ELOC;
elseif (~ischar(g.elocs)) & ~isstruct(g.elocs)
error('Channel location file must be a valid text file.');
end
if (~isnumeric(g.alpha) | length(g.alpha)~=1)
error('timef(): Value of g.alpha must be a number.\n');
elseif (round(g.naccu*g.alpha) < 2)
myprintf(g.verbose,'Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu);
g.naccu = round(2/g.alpha);
myprintf(g.verbose,' Increasing the number of bootstrap iterations to %d\n',g.naccu);
end
if g.alpha>0.5 | g.alpha<=0
error('Value of g.alpha is out of the allowed range (0.00,0.5).');
end
if ~isnan(g.alpha)
if g.baseboot > 0
myprintf(g.verbose,'Bootstrap analysis will use data in baseline (pre-0 centered) subwindows only.\n')
else
myprintf(g.verbose,'Bootstrap analysis will use data in all subwindows.\n')
end
end
if ~isnumeric(g.vert)
error('vertical line(s) option must be a vector');
else
if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2)
error('vertical line(s) time out-of-bound');
end;
end;
if ~isnan (g.rboot)
if size(g.rboot) == [1,1]
if g.cycles == 0
g.rboot = g.rboot*ones(g.winsize*g.padratio/2);
end
end
end;
if ~isempty(g.mtaper) % mutitaper, inspired from Bijan Pesaran matlab function
if length(g.mtaper) < 3
%error('mtaper arguement must be [N W] or [N W K]');
if g.mtaper(1) * g.mtaper(2) < 1
error('mtaper 2 first arguments'' product must be higher than 1');
end;
if length(g.mtaper) == 2
g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1);
end
if length(g.mtaper) == 3
if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1
error('mtaper number too high (maximum (2*N*W-1))');
end;
end
disp(['Using ' num2str(g.mtaper(3)) ' tapers.']);
NW = g.mtaper(1)*g.mtaper(2); % product NW
N = g.mtaper(1)*g.srate;
[e,v] = dpss(N, NW, 'calc');
e=e(:,1:g.mtaper(3));
g.alltapers = e;
else
g.alltapers = g.mtaper;
disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix');
end;
g.winsize = size(g.alltapers, 1);
g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow
%nfk = floor([0 g.maxfreq]./g.srate.*g.pad); % not used any more
%g.padratio = 2*nfk(2)/g.winsize;
g.padratio = g.pad/g.winsize;
%compute number of frequencies
%nf = max(256, g.pad*2^nextpow2(g.winsize+1));
%nfk = floor([0 g.maxfreq]./g.srate.*nf);
%freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also work in the case of a FFT
end;
switch lower(g.plotphase)
case { 'on', 'off' }, ;
otherwise error('plotphase must be either on or off');
end;
switch lower(g.plotersp)
case { 'on', 'off' }, ;
otherwise error('plotersp must be either on or off');
end;
switch lower(g.plotitc)
case { 'on', 'off' }, ;
otherwise error('plotitc must be either on or off');
end;
switch lower(g.detrep)
case { 'on', 'off' }, ;
otherwise error('detrep must be either on or off');
end;
switch lower(g.detret)
case { 'on', 'off' }, ;
otherwise error('detret must be either on or off');
end;
switch lower(g.phsamp)
case { 'on', 'off' }, ;
otherwise error('phsamp must be either on or off');
end;
if ~isnumeric(g.linewidth)
error('linewidth must be numeric');
end;
if ~isnumeric(g.naccu)
error('naccu must be numeric');
end;
if ~isnumeric(g.baseline)
error('baseline must be numeric');
end;
switch g.baseboot
case {0,1}, ;
otherwise, error('baseboot must be 0 or 1');
end;
switch g.type
case { 'coher', 'phasecoher', 'phasecoher2' },;
otherwise error('Type must be either ''coher'' or ''phasecoher''');
end;
if isnan(g.baseline)
g.unitpower = 'uV/Hz';
else
g.unitpower = 'dB';
end;
if (g.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%%
freqs = linspace(0, g.srate/2, g.padratio*g.winsize/2+1);
freqs = freqs(2:end);
win = hanning(g.winsize);
P = zeros(g.padratio*g.winsize/2,g.timesout); % summed power
PP = zeros(g.padratio*g.winsize/2,g.timesout); % power
R = zeros(g.padratio*g.winsize/2,g.timesout); % mean coherence
RR = zeros(g.padratio*g.winsize/2,g.timesout); % (coherence)
Pboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap power
Rboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap coher
Rn = zeros(1,g.timesout);
Rbn = 0;
switch g.type
case { 'coher' 'phasecoher2' },
cumulX = zeros(g.padratio*g.winsize/2,g.timesout);
cumulXboot = zeros(g.padratio*g.winsize/2,g.naccu);
case 'phasecoher'
switch g.phsamp
case 'on'
cumulX = zeros(g.padratio*g.winsize/2,g.timesout);
end
end;
else % %%%%%%%%%%%%%%%%%% cycles>0, Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%
freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2;
dispf = find(freqs <= g.maxfreq);
freqs = freqs(dispf);
win = dftfilt(g.winsize,g.maxfreq/g.srate,g.cycles,g.padratio,g.cyclesfact);
P = zeros(size(win,2),g.timesout); % summed power
R = zeros(size(win,2),g.timesout); % mean coherence
PP = repmat(NaN,size(win,2),g.timesout); % initialize with NaN
RR = repmat(NaN,size(win,2),g.timesout); % initialize with NaN
Pboot = zeros(size(win,2),g.naccu); % summed bootstrap power
Rboot = zeros(size(win,2),g.naccu); % summed bootstrap coher
Rn = zeros(1,g.timesout);
Rbn = 0;
switch g.type
case { 'coher' 'phasecoher2' },
cumulX = zeros(size(win,2),g.timesout);
cumulXboot = zeros(size(win,2),g.naccu);
case 'phasecoher'
switch g.phsamp
case 'on'
cumulX = zeros(size(win,2),g.timesout);
end
end;
end
switch g.phsamp
case 'on'
PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times)
end % phs amp
wintime = 1000/g.srate*(g.winsize/2); % (1000/g.srate)*(g.winsize/2);
times = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime];
ERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001];
ERPindices = [];
for ti=times
[tmp indx] = min(abs(ERPtimes-ti));
ERPindices = [ERPindices indx];
end
ERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers
if ~isempty(find(times < g.baseline))
baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows
else
baseln = 1:length(times); % use all times as baseline
end
if ~isnan(g.alpha) & length(baseln)==0
myprintf(g.verbose,'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline)
return
elseif ~isnan(g.alpha) & g.baseboot
myprintf(g.verbose,' %d bootstrap windows in baseline (center times < %g).\n',...
length(baseln), g.baseline)
end
dispf = find(freqs <= g.maxfreq);
stp = (g.frames-g.winsize)/(g.timesout-1);
myprintf(g.verbose,'Computing Event-Related Spectral Perturbation (ERSP) and\n');
switch g.type
case 'phasecoher', myprintf(g.verbose,' Inter-Trial Phase Coherence (ITC) images based on %d trials\n',length(X)/g.frames);
case 'phasecoher2', myprintf(g.verbose,' Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\n',length(X)/g.frames);
case 'coher', myprintf(g.verbose,' Linear Inter-Trial Coherence (ITC) images based on %d trials\n',length(X)/g.frames);
end;
myprintf(g.verbose,' of %d frames sampled at %g Hz.\n',g.frames,g.srate);
myprintf(g.verbose,'Each trial contains samples from %d ms before to\n',g.tlimits(1));
myprintf(g.verbose,' %.0f ms after the timelocking event.\n',g.tlimits(2));
myprintf(g.verbose,'The window size used is %d samples (%g ms) wide.\n',g.winsize,2*wintime);
myprintf(g.verbose,'The window is applied %d times at an average step\n',g.timesout);
myprintf(g.verbose,' size of %g samples (%g ms).\n',stp,1000*stp/g.srate);
myprintf(g.verbose,'Results are oversampled %d times; the %d frequencies\n',g.padratio,length(dispf));
myprintf(g.verbose,' displayed are from %2.1f Hz to %3.1f Hz.\n',freqs(dispf(1)),freqs(dispf(end)));
if ~isnan(g.alpha)
myprintf(g.verbose,'Only significant values (bootstrap p<%g) will be colored;\n',g.alpha)
myprintf(g.verbose,' non-significant values will be plotted in green\n');
end
trials = length(X)/g.frames;
baselength = length(baseln);
myprintf(g.verbose,'\nOf %d trials total, processing trial:',trials);
% detrend over epochs (trials) if requested
% -----------------------------------------
switch g.detrep
case 'on'
X = reshape(X, g.frames, length(X)/g.frames);
X = X - mean(X,2)*ones(1, length(X(:))/g.frames);
X = X(:)';
end;
for i=1:trials
if (rem(i,100)==0)
myprintf(g.verbose,'\n');
end
if (rem(i,10) == 0)
myprintf(g.verbose,'%d',i);
elseif (rem(i,2) == 0)
myprintf(g.verbose,'.');
end
ERP = blockave(X,g.frames); % compute the ERP trial average
Wn = zeros(1,g.timesout);
for j=1:g.timesout,
tmpX = X([1:g.winsize]+floor((j-1)*stp)+(i-1)*g.frames);
% pull out data g.frames
tmpX = tmpX - mean(tmpX); % remove the mean for that window
switch g.detret, case 'on', tmpX = detrend(tmpX); end;
if ~any(isnan(tmpX))
if (g.cycles == 0) % FFT
if ~isempty(g.mtaper) % apply multitaper (no hanning window)
tmpXMT = fft(g.alltapers .* ...
(tmpX(:) * ones(1,size(g.alltapers,2))), g.pad);
%tmpXMT = tmpXMT(nfk(1)+1:nfk(2),:);
tmpXMT = tmpXMT(2:g.padratio*g.winsize/2+1,:);
PP(:,j) = mean(abs(tmpXMT).^2, 2);
% power; can also ponderate multitaper by their eigenvalues v
tmpX = win .* tmpX(:);
tmpX = fft(tmpX, g.pad);
tmpX = tmpX(2:g.padratio*g.winsize/2+1);
else
% TF and MC (12/2006): Calculation changes made so that
% power can be correctly calculated from ERSP.
tmpX = win .* tmpX(:);
tmpX = fft(tmpX,g.padratio*g.winsize);
tmpX = tmpX / g.winsize; % TF and MC (12/11/2006): normalization, divide by g.winsize
tmpX = tmpX(2:g.padratio*g.winsize/2+1);
PP(:,j) = 2/0.375*abs(tmpX).^2; % power
% TF and MC (12/14/2006): multiply by 2 account for negative frequencies,
% Counteract the reduction by a factor 0.375
% that occurs as a result of cosine (Hann) tapering. Refer to Bug 446
end;
else % wavelet
if ~isempty(g.mtaper) % apply multitaper
tmpXMT = g.alltapers .* (tmpX(:) * ones(1,size(g.alltapers,2)));
tmpXMT = transpose(win) * tmpXMT;
PP(:,j) = mean(abs(tmpXMT).^2, 2); % power
tmpX = transpose(win) * tmpX(:);
else
tmpX = transpose(win) * tmpX(:);
PP(:,j) = abs(tmpX).^2; % power
end
end
if abs(tmpX) < eps % If less than smallest possible machine value
% (i.e. if it's zero) then call it 0.
RR(:,j) = zeros(size(RR(:,j)));
else
switch g.type
case { 'coher' },
RR(:,j) = tmpX;
cumulX(:,j) = cumulX(:,j)+abs(tmpX).^2;
case { 'phasecoher2' },
RR(:,j) = tmpX;
cumulX(:,j) = cumulX(:,j)+abs(tmpX);
case 'phasecoher',
RR(:,j) = tmpX ./ abs(tmpX); % normalized cross-spectral vector
switch g.phsamp
case 'on'
cumulX(:,j) = cumulX(:,j)+abs(tmpX); % accumulate for PA
end
end;
end
Wn(j) = 1;
end
switch g.phsamp
case 'on' % PA (freq x freq x time)
PA(:,:,j) = PA(:,:,j) + (tmpX ./ abs(tmpX)) * ((PP(:,j)))';
% cross-product: unit phase (column)
% times amplitude (row)
end
end % window
if ~isnan(g.alpha) % save surrogate data for bootstrap analysis
j = 1;
goodbasewins = find(Wn==1);
if g.baseboot % use baseline windows only
goodbasewins = find(goodbasewins<=baselength);
end
ngdbasewins = length(goodbasewins);
if ngdbasewins>1
while j <= g.naccu
i=ceil(rand*ngdbasewins);
i=goodbasewins(i);
Pboot(:,j) = Pboot(:,j) + PP(:,i);
Rboot(:,j) = Rboot(:,j) + RR(:,i);
switch g.type
case 'coher', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX).^2;
case 'phasecoher2', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX);
end;
j = j+1;
end
Rbn = Rbn + 1;
end
end % bootstrap
Wn = find(Wn>0);
if length(Wn)>0
P(:,Wn) = P(:,Wn) + PP(:,Wn); % add non-NaN windows
R(:,Wn) = R(:,Wn) + RR(:,Wn);
Rn(Wn) = Rn(Wn) + ones(1,length(Wn)); % count number of addends
end
end % trial
% if coherence, perform the division
% ----------------------------------
switch g.type
case 'coher',
R = R ./ ( sqrt( trials*cumulX ) );
if ~isnan(g.alpha)
Rboot = Rboot ./ ( sqrt( trials*cumulXboot ) );
end;
case 'phasecoher2',
R = R ./ ( cumulX );
if ~isnan(g.alpha)
Rboot = Rboot ./ cumulXboot;
end;
case 'phasecoher',
R = R ./ (ones(size(R,1),1)*Rn);
end;
switch g.phsamp
case 'on'
tmpcx(1,:,:) = cumulX; % allow ./ below
for j=1:g.timesout
PA(:,:,j) = PA(:,:,j) ./ repmat(PP(:,j)', [size(PP,1) 1]);
end
end
if min(Rn) < 1
myprintf(g.verbose,'timef(): No valid timef estimates for windows %s of %d.\n',...
int2str(find(Rn==0)),length(Rn));
Rn(find(Rn<1))==1;
return
end
P = P ./ (ones(size(P,1),1) * Rn);
if isnan(g.powbase)
myprintf(g.verbose,'\nComputing the mean baseline spectrum\n');
mbase = mean(P(:,baseln),2)';
else
myprintf(g.verbose,'Using the input baseline spectrum\n');
mbase = g.powbase;
end
if ~isnan( g.baseline ) & ~isnan( mbase )
P = 10 * (log10(P) - repmat(log10(mbase(1:size(P,1)))',[1 g.timesout])); % convert to (10log10) dB
else
P = 10 * log10(P);
end;
Rsign = sign(imag(R));
if nargout > 7
for lp = 1:size(R,1)
Rphase(lp,:) = rem(angle(R(lp,:)),2*pi); % replaced obsolete phase() -sm 2/1/6
end
Rphase(find(Rphase>pi)) = 2*pi-Rphase(find(Rphase>pi));
Rphase(find(Rphase<-pi)) = -2*pi-Rphase(find(Rphase<-pi));
end
R = abs(R); % convert coherence vector to magnitude
if ~isnan(g.alpha) % if bootstrap analysis included . . .
if Rbn>0
i = round(g.naccu*g.alpha);
if isnan(g.pboot)
Pboot = Pboot / Rbn; % normalize
if ~isnan( g.baseline )
Pboot = 10 * (log10(Pboot) - repmat(log10(mbase)',[1 g.naccu]));
else
Pboot = 10 * log10(Pboot);
end;
Pboot = sort(Pboot');
Pboot = [mean(Pboot(1:i,:)) ; mean(Pboot(g.naccu-i+1:g.naccu,:))];
else
Pboot = g.pboot;
end
if isnan(g.rboot)
Rboot = abs(Rboot) / Rbn;
Rboot = sort(Rboot');
Rboot = mean(Rboot(g.naccu-i+1:g.naccu,:));
else
Rboot = g.rboot;
end
else
myprintf(g.verbose,'No valid bootstrap trials...!\n');
end
end
switch lower(g.plotitc)
case 'on',
switch lower(g.plotersp),
case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1;
case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1;
end;
case 'off', ordinate1 = 0.1; height = 0.9;
switch lower(g.plotersp),
case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1;
case 'off', g.plot = 0;
end;
end;
if g.plot
myprintf(g.verbose,'\nNow plotting...\n');
set(gcf,'DefaultAxesFontSize',AXES_FONT)
colormap(jet(256));
pos = get(gca,'position');
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)];
end;
switch lower(g.plotersp)
case 'on'
%
%%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%%
%
h(1) = subplot('Position',[.1 ordinate1 .9 height].*s+q);
PP = P; % PP will be ERSP power after
if ~isnan(g.alpha) % zero out nonsignif. power differences
PP(find((PP > repmat(Pboot(1,:)',[1 g.timesout])) ...
& (PP < repmat(Pboot(2,:)',[1 g.timesout])))) = 0;
end
if ERSP_CAXIS_LIMIT == 0
ersp_caxis = [-1 1]*1.1*max(max(abs(P(dispf,:))));
else
ersp_caxis = ERSP_CAXIS_LIMIT*[-1 1];
end
if ~isnan( g.baseline )
imagesc(times,freqs(dispf),PP(dispf,:),ersp_caxis);
else
imagesc(times,freqs(dispf),PP(dispf,:));
end;
set(gca,'ydir',g.hzdir); % make frequency ascend or descend
if ~isempty(g.erspmax)
caxis([-g.erspmax g.erspmax]);
end;
hold on
plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); % plot time 0
if ~isnan(g.marktimes) % plot marked time
for mt = g.marktimes(:)'
plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth);
end
end
hold off
set(h(1),'YTickLabel',[],'YTick',[])
set(h(1),'XTickLabel',[],'XTick',[])
if ~isempty(g.vert)
for index = 1:length(g.vert)
line([g.vert(index), g.vert(index)], [min(freqs(dispf)) max(freqs(dispf))], 'linewidth', 1, 'color', 'm');
end;
end;
h(2) = gca;
h(3) = cbar('vert'); % ERSP colorbar axes
set(h(2),'Position',[.1 ordinate1 .8 height].*s+q)
set(h(3),'Position',[.95 ordinate1 .05 height].*s+q)
title([ 'ERSP(' g.unitpower ')' ])
E = [min(P(dispf,:));max(P(dispf,:))];
h(4) = subplot('Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal ERSP means
% below the ERSP image
plot(times,E,[0 0],...
[min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3], ...
'--m','LineWidth',g.linewidth)
axis([min(times) max(times) ...
min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3])
tick = get(h(4),'YTick');
set(h(4),'YTick',[tick(1) ; tick(end)])
set(h(4),'YAxisLocation','right')
set(h(4),'TickLength',[0.020 0.025]);
xlabel('Time (ms)')
ylabel( g.unitpower )
E = 10 * log10(mbase(dispf));
h(5) = subplot('Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum
% to left of ERSP image
plot(freqs(dispf),E,'LineWidth',g.linewidth)
if ~isnan(g.alpha)
hold on;
plot(freqs(dispf),Pboot(:,dispf)+[E;E],'g', 'LineWidth',g.linewidth);
plot(freqs(dispf),Pboot(:,dispf)+[E;E],'k:','LineWidth',g.linewidth)
end
axis([freqs(1) freqs(max(dispf)) min(E)-max(abs(E))/3 max(E)+max(abs(E))/3])
tick = get(h(5),'YTick');
if (length(tick)>1)
set(h(5),'YTick',[tick(1) ; tick(end-1)])
end
set(h(5),'TickLength',[0.020 0.025]);
set(h(5),'View',[90 90])
xlabel('Frequency (Hz)')
ylabel( g.unitpower )
if strcmp(g.hzdir,'normal')
freqdir = 'reverse';
else
freqdir = 'normal';
end
set(h(5),'xdir',freqdir); % make frequency ascend or descend
end;
switch lower(g.plotitc)
case 'on'
%
%%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%%
%
h(6) = subplot('Position',[.1 ordinate2 .9 height].*s+q); % ITC image
RR = R; % RR is the masked ITC (R)
if ~isnan(g.alpha)
RR(find(RR < repmat(Rboot(1,:)',[1 g.timesout]))) = 0;
end
if ITC_CAXIS_LIMIT == 0
coh_caxis = min(max(max(R(dispf,:))),1)*[-1 1]; % 1 WAS 0.4 !
else
coh_caxis = ITC_CAXIS_LIMIT*[-1 1];
end
if exist('Rsign') & strcmp(g.plotphase, 'on')
imagesc(times,freqs(dispf),Rsign(dispf,:).*RR(dispf,:),coh_caxis); % <---
else
imagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % <---
end
if ~isempty(g.itcmax)
caxis([-g.itcmax g.itcmax]);
end;
tmpcaxis = caxis;
set(gca,'ydir',g.hzdir); % make frequency ascend or descend
hold on
plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth);
if ~isnan(g.marktimes)
for mt = g.marktimes(:)'
plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth);
end
end
hold off
set(h(6),'YTickLabel',[],'YTick',[])
set(h(6),'XTickLabel',[],'XTick',[])
if ~isempty(g.vert)
for index = 1:length(g.vert)
line([g.vert(index), g.vert(index)], ...
[min(freqs(dispf)) max(freqs(dispf))], ...
'linewidth', 1, 'color', 'm');
end;
end;
h(7) = gca;
h(8) = cbar('vert');
%h(9) = get(h(8),'Children');
set(h(7),'Position',[.1 ordinate2 .8 height].*s+q)
set(h(8),'Position',[.95 ordinate2 .05 height].*s+q)
set(h(8),'YLim',[0 tmpcaxis(2)]);
title('ITC')
%
%%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% E = mean(R(dispf,:));
ERPmax = max(ERP);
ERPmin = min(ERP);
ERPmax = ERPmax + 0.1*(ERPmax-ERPmin);
ERPmin = ERPmin - 0.1*(ERPmax-ERPmin);
h(10) = subplot('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP
plot(ERPtimes,ERP(ERPindices),...
[0 0],[ERPmin ERPmax],'--m','LineWidth',g.linewidth);
hold on; plot([times(1) times(length(times))],[0 0], 'k');
axis([min(ERPtimes) max(ERPtimes) ERPmin ERPmax]);
tick = get(h(10),'YTick');
set(h(10),'YTick',[tick(1) ; tick(end)])
set(h(10),'TickLength',[0.02 0.025]);
set(h(10),'YAxisLocation','right')
xlabel('Time (ms)')
ylabel('\muV')
if (~isempty(g.topovec))
if length(g.topovec) ~= 1, ylabel(''); end; % ICA component
end;
E = mean(R(dispf,:)');
h(11) = subplot('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean
% ITC left of the ITC image
if ~isnan(g.alpha)
plot(freqs(dispf),E,'LineWidth',g.linewidth); hold on;
plot(freqs(dispf),Rboot(dispf),'g', 'LineWidth',g.linewidth);
plot(freqs(dispf),Rboot(dispf),'k:','LineWidth',g.linewidth);
axis([freqs(1) freqs(max(dispf)) 0 max([E Rboot(dispf)])+max(E)/3])
else
plot(freqs(dispf),E,'LineWidth',g.linewidth)
axis([freqs(1) freqs(max(dispf)) min(E)-max(E)/3 max(E)+max(E)/3])
end
tick = get(h(11),'YTick');
set(h(11),'YTick',[tick(1) ; tick(length(tick))])
set(h(11),'View',[90 90])
set(h(11),'TickLength',[0.020 0.025]);
xlabel('Frequency (Hz)')
ylabel('ERP')
if strcmp(g.hzdir,'normal')
freqdir = 'reverse';
else
freqdir = 'normal';
end
set(gca,'xdir',freqdir); % make frequency ascend or descend
%
%%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%%
%
if (~isempty(g.topovec))
h(12) = subplot('Position',[-.1 .43 .2 .14].*s+q);
if length(g.topovec) == 1
topoplot(g.topovec,g.elocs,'electrodes','off', ...
'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo);
else
topoplot(g.topovec,g.elocs,'electrodes','off', 'chaninfo', g.chaninfo);
end;
axis('square')
end
end; % switch
if g.plot
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
if (length(g.title) > 0)
axes('Position',pos,'Visible','Off');
h(13) = text(-.05,1.01,g.title);
set(h(13),'VerticalAlignment','bottom')
set(h(13),'HorizontalAlignment','left')
set(h(13),'FontSize',TITLE_FONT);
end
axcopy(gcf);
end;
% symmetric Hanning tapering function
% -----------------------------------
function w = hanning(n)
if ~rem(n,2)
w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1)));
w = [w; w(end:-1:1)];
else
w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1)));
w = [w; w(end-1:-1:1)];
end
function myprintf(verbose, varargin)
if strcmpi(verbose, 'on')
fprintf(varargin{:});
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.