Home > SuperSegger > gate > gateTool.m

gateTool

PURPOSE ^

gateTool : tool for gating and plotting functionality of clists.

SYNOPSIS ^

function [clist, out] = gateTool(varargin)

DESCRIPTION ^

 gateTool : tool for gating and plotting functionality of clists.

 GATETOOL( [clist,clist cell array,directory,filename], [command string], [argument], ... ) 
 
 clist must be (i) a clist struct or (ii) a cell array of clists or (iii)
 a data directory, xy1 directory or a clist file name. 

  If there are no arguments specified, the 'strip' command is run

Clist modification commands:

 'merge'      : Merge all clist input into a single output clist (no
                arguments accepted)

 'name', str  : Add name in str to all input clists as a label                 

 'color', cc  : Set color cc for all clists

 'strip'      : Remove all un-gated cells (no arguments)           

 'make', ind  : Gate on indices in ind. Specify either 1 or 2 as a vector 
                index names are stored in def and can be view by running 
                the def command. If the ind is a structure it assumes it 
                is a preformed gate and adds it to the gate array in all 
                clists. Any gating is performed on all clists input.  

 'squeeze'     : make a clist vertical so all entries are treated as
                 identifcal conditions.

 'expand'      : make a clist horizontal so all entries are treated as
                 different conditions

 'add', data, name : add a field (name) to the clist data with values
                 (data)

 'add3D' data, name : add a field (name) to the clist data with values
                 (data)

 'get', index  : gets data from data column index  
%
 'getgate', index : gets the indexed gate.

Visualization commands:

 'show', ind   : This command will make a figure for viewing without 
                 modifying the clist. ind is either and index or pair of 
                 indices specifying what is to be visualized. If no ind is 
                 passed then all gates are displayed on a single clist 
                 input         

 'kde'         : Make either a 1 or 2D KDE (depending on dimension of ind)
                 'show' must be called as well.

 {'time','3D'} : Make a temporal plot of single cell dynamics for one index
                 'show' must be called as well.

 'hist'        : Make a 1 or 2D histogram (depending on dimension of ind)
                 'show' must be called as well.   
           
 'dot'         : Make a dot plot. Dim of ind must equal 2.
                 'show' must be called as well.

 'line'        :


 'log', axes   : Set of axes to set with log scales. axes = [1,2,3] will 
                 set x, y and color axis to have log scale.

 'den'         : Normalize KDE and hist like a probability density

 'cond'        : Normalize like a conditional probability density

 'no clear'    : Do not run clear figure (clf) before drawing.

 'rk', rk      : radius of the gaussian kernel for KDE

 'rm', rm      : radius of the point mask for KDE              

 'inv'         : invert 2D hist/KDE image for printing 

 'mult', mult  : set the resolution for the KDE. Set the number of pixels
                 in the image created to make ke 

 'bin', bin    : set the binning for the hist and KDE. In 1D, if bin is a
                 scalar it is interpretted as the number of bins. If it is
                 a vector it is assumed to be the bin centers. In 2D, if
                 bun is a vector, it is interpretted to be a vector of bin
                 numbers for the two dimensions. If it is a cell array, it
                 is assumed to be two vectors of centers.


 'err'         : show error in 1D histograms and kde's

 'stat'        : show statistics for a show command. Only one index.

 'newfig'      : draws new figures for each clist

Other commands:

 'def'         : Show all the channel definitions at the command line

 'def3D'       : Show all the temporal channel definitions at the command
                 line

 'xls', filename : export an excel doc with the clist data. Need to have
                   excel installed to export. (Not my fault.)

 'csv', filename, [ind] : export a csv doc with the clist data.

 'save', filename : Save .mat file.

 'units', units : set the multiplier for the data to set the desired units

 'drill'       : Use recursive loading trhough a directory tree to any
                 level.

 Copyright (C) 2016 Wiggins Lab
 Written by Paul Wiggins.
 University of Washington, 2016
 This file is part of SuperSegger.

 SuperSegger is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 SuperSegger 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 SuperSegger.  If not, see <http://www.gnu.org/licenses/>.

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function [clist, out] = gateTool(varargin)
0002 % gateTool : tool for gating and plotting functionality of clists.
0003 %
0004 % GATETOOL( [clist,clist cell array,directory,filename], [command string], [argument], ... )
0005 %
0006 % clist must be (i) a clist struct or (ii) a cell array of clists or (iii)
0007 % a data directory, xy1 directory or a clist file name.
0008 %
0009 %  If there are no arguments specified, the 'strip' command is run
0010 %
0011 %Clist modification commands:
0012 %
0013 % 'merge'      : Merge all clist input into a single output clist (no
0014 %                arguments accepted)
0015 %
0016 % 'name', str  : Add name in str to all input clists as a label
0017 %
0018 % 'color', cc  : Set color cc for all clists
0019 %
0020 % 'strip'      : Remove all un-gated cells (no arguments)
0021 %
0022 % 'make', ind  : Gate on indices in ind. Specify either 1 or 2 as a vector
0023 %                index names are stored in def and can be view by running
0024 %                the def command. If the ind is a structure it assumes it
0025 %                is a preformed gate and adds it to the gate array in all
0026 %                clists. Any gating is performed on all clists input.
0027 %
0028 % 'squeeze'     : make a clist vertical so all entries are treated as
0029 %                 identifcal conditions.
0030 %
0031 % 'expand'      : make a clist horizontal so all entries are treated as
0032 %                 different conditions
0033 %
0034 % 'add', data, name : add a field (name) to the clist data with values
0035 %                 (data)
0036 %
0037 % 'add3D' data, name : add a field (name) to the clist data with values
0038 %                 (data)
0039 %
0040 % 'get', index  : gets data from data column index
0041 %%
0042 % 'getgate', index : gets the indexed gate.
0043 %
0044 %Visualization commands:
0045 %
0046 % 'show', ind   : This command will make a figure for viewing without
0047 %                 modifying the clist. ind is either and index or pair of
0048 %                 indices specifying what is to be visualized. If no ind is
0049 %                 passed then all gates are displayed on a single clist
0050 %                 input
0051 %
0052 % 'kde'         : Make either a 1 or 2D KDE (depending on dimension of ind)
0053 %                 'show' must be called as well.
0054 %
0055 % {'time','3D'} : Make a temporal plot of single cell dynamics for one index
0056 %                 'show' must be called as well.
0057 %
0058 % 'hist'        : Make a 1 or 2D histogram (depending on dimension of ind)
0059 %                 'show' must be called as well.
0060 %
0061 % 'dot'         : Make a dot plot. Dim of ind must equal 2.
0062 %                 'show' must be called as well.
0063 %
0064 % 'line'        :
0065 %
0066 %
0067 % 'log', axes   : Set of axes to set with log scales. axes = [1,2,3] will
0068 %                 set x, y and color axis to have log scale.
0069 %
0070 % 'den'         : Normalize KDE and hist like a probability density
0071 %
0072 % 'cond'        : Normalize like a conditional probability density
0073 %
0074 % 'no clear'    : Do not run clear figure (clf) before drawing.
0075 %
0076 % 'rk', rk      : radius of the gaussian kernel for KDE
0077 %
0078 % 'rm', rm      : radius of the point mask for KDE
0079 %
0080 % 'inv'         : invert 2D hist/KDE image for printing
0081 %
0082 % 'mult', mult  : set the resolution for the KDE. Set the number of pixels
0083 %                 in the image created to make ke
0084 %
0085 % 'bin', bin    : set the binning for the hist and KDE. In 1D, if bin is a
0086 %                 scalar it is interpretted as the number of bins. If it is
0087 %                 a vector it is assumed to be the bin centers. In 2D, if
0088 %                 bun is a vector, it is interpretted to be a vector of bin
0089 %                 numbers for the two dimensions. If it is a cell array, it
0090 %                 is assumed to be two vectors of centers.
0091 %
0092 %
0093 % 'err'         : show error in 1D histograms and kde's
0094 %
0095 % 'stat'        : show statistics for a show command. Only one index.
0096 %
0097 % 'newfig'      : draws new figures for each clist
0098 %
0099 %Other commands:
0100 %
0101 % 'def'         : Show all the channel definitions at the command line
0102 %
0103 % 'def3D'       : Show all the temporal channel definitions at the command
0104 %                 line
0105 %
0106 % 'xls', filename : export an excel doc with the clist data. Need to have
0107 %                   excel installed to export. (Not my fault.)
0108 %
0109 % 'csv', filename, [ind] : export a csv doc with the clist data.
0110 %
0111 % 'save', filename : Save .mat file.
0112 %
0113 % 'units', units : set the multiplier for the data to set the desired units
0114 %
0115 % 'drill'       : Use recursive loading trhough a directory tree to any
0116 %                 level.
0117 %
0118 % Copyright (C) 2016 Wiggins Lab
0119 % Written by Paul Wiggins.
0120 % University of Washington, 2016
0121 % This file is part of SuperSegger.
0122 %
0123 % SuperSegger is free software: you can redistribute it and/or modify
0124 % it under the terms of the GNU General Public License as published by
0125 % the Free Software Foundation, either version 3 of the License, or
0126 % (at your option) any later version.
0127 %
0128 % SuperSegger is distributed in the hope that it will be useful,
0129 % but WITHOUT ANY WARRANTY; without even the implied warranty of
0130 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0131 % GNU General Public License for more details.
0132 %
0133 % You should have received a copy of the GNU General Public License
0134 % along with SuperSegger.  If not, see <http://www.gnu.org/licenses/>.
0135 %
0136 
0137 %% process the input arguments
0138 data = intProcessInput( varargin );
0139 
0140 
0141 %% make a new gate if required
0142 if data.merge_flag
0143     data.clist = intDoMerge( data.clist, [], data.skip3D_flag );
0144 end
0145 
0146 
0147 
0148 
0149 %% make a new gate if required
0150 if data.make_flag
0151     data = intMakeGate( data, data.ind );
0152 end
0153 
0154 %% Show the gates if the show flag is true
0155 if data.show_all_flag
0156     data.clist = intShowAll( data.clist, 1, data );
0157 elseif data.show_flag
0158     data = intShow( data );
0159 end
0160 
0161 %% strip out data that was gated out if the strip flag is set;
0162 if data.strip_flag
0163     data = intDoStrip( data );
0164 end
0165 
0166 
0167 %% Do export
0168 if data.export_flag
0169     intcsv( data.clist, data );
0170 end
0171 
0172 %% make the output
0173 
0174 if data.get_flag
0175     if data.time_flag
0176         out = squeeze(intGet3D( data.clist, data.g_ind ));
0177     else
0178         out = intGet( data.clist, data.g_ind );
0179     end
0180 elseif data.stat_flag
0181     %out = intGetCellNum( data.clist );
0182     %disp( ['Gated cells: ',num2str(out(1))] );
0183     %disp( ['Total cells:  ',num2str(out(2))] );
0184     %disp( [num2str(100*out(1)/out(2)),' %'] );
0185     intShowKS( data );
0186 elseif data.get_gate_flag
0187     
0188     if ~data.time_flag
0189         if data.which_gate <= numel( data.clist.gate )
0190             out = data.clist.gate(data.which_gate);
0191         else
0192             error( ['There are only ', num2str( numel( data.clist.gate ) ), ' gates.'] );
0193         end
0194     else
0195         if ~isfield( data.clist, 'gate3D' )
0196             error( 'There is not gate3D field.' );
0197         else
0198             if data.which_gate <= numel( data.clist.gate3D )
0199                 out = data.clist.gate3D(data.which_gate);
0200             else
0201                 error( ['There are only ', num2str( numel( data.clist.gate3D ) ), ' gates.'] );
0202             end
0203         end
0204         
0205     end
0206 end
0207 
0208 
0209 clist = data.clist;
0210 
0211 if data.save_flag
0212     intSaveClist( data ); 
0213 end
0214 
0215 end
0216 
0217 %% internal funciton that processes that input arguments
0218 function data = intProcessInput( varargin )
0219 
0220 varargin = varargin{1};
0221 nargin   = numel( varargin );
0222 
0223 data.make_flag      = false;
0224 
0225 data.strip_flag     = false;
0226 data.log_flag       = false([1,3]);
0227 data.merge_flag     = false;
0228 data.bin_flag       = false;
0229 data.hist_flag      = false;
0230 data.kde_flag       = false;
0231 data.time_flag      = false;
0232 data.dot_flag       = false;
0233 data.dothist_flag   = false;
0234 data.inv_flag       = false;
0235 data.get_flag       = false;
0236 data.stat_flag      = false;
0237 data.skip3D_flag    = false;
0238 data.export_flag    = false;
0239 data.drill_flag     = false;
0240 data.error_flag     = false;
0241 data.newfig_flag    = false;
0242 data.line_flag      = false;
0243 data.save_flag      = false;
0244 data.noshow_flag    = false;
0245 
0246 data.trace_flag     = false;
0247 
0248 data.get_gate_flag  = false;
0249 data.name_flag      = false;
0250 data.den_flag       = false;
0251 data.noclear_flag   = false;
0252 
0253 data.show_flag      = false;
0254 data.show_all_flag  = false;
0255 data.array_flag     = false;
0256 
0257 data.clist      = [];
0258 data.h          = [];
0259 data.legend     = {};
0260 
0261 data.ind        = [];
0262 data.bin        = [];
0263 data.color      = [];
0264 data.rk         = [];
0265 data.rm         = [];
0266 data.g_ind      = [];
0267 
0268 data.units      = [1,1];
0269 data.fig_ptr    = [];
0270 data.minBinNum  = 5;
0271 data.multi      = 500;
0272 
0273 data.im = {};
0274 
0275 
0276 data.cond_flag  = false;
0277 
0278 load_flag = false;
0279 
0280 if nargin == 0
0281     error( 'gate must have at least one argument (a clist)' );
0282 else
0283     next_arg = varargin{1};
0284     
0285     if any(strcmp( 'time',varargin )) || ...
0286             any(strcmp( '3d',varargin ))   || ...
0287             any(strcmp( '3D',varargin ))
0288         data.time_flag = true;
0289     end
0290     
0291     if any(strcmp( 'noshow',varargin )) 
0292         data.noshow_flag = true;
0293     end
0294     
0295     if ischar( next_arg )
0296         
0297         if any(strcmp( 'drill',varargin ))
0298             data.drill_flag = true;
0299         end
0300         
0301         
0302         
0303         next_arg = intLoadClist( next_arg, data );
0304         load_flag = true;
0305     end
0306     
0307     if (~iscell( next_arg )) && (~isstruct( next_arg ))
0308         error( 'First argument must be a clist' );
0309     end
0310     
0311     % fix naming of def3D
0312     clist = next_arg;
0313     clist = intFixDef3D( clist );
0314 
0315     data.clist = clist;
0316     
0317     
0318     if iscell( next_arg );
0319         data.array_flag  = true;
0320     end
0321     
0322     counter = 1;
0323     
0324     % set the strip if no arguments are specified
0325     if  nargin == 1 && ~load_flag
0326         data.strip_flag = true;
0327     end
0328     
0329     
0330     while counter < nargin
0331         
0332         counter = counter + 1;
0333         next_arg = varargin{counter};
0334         
0335         if ~ischar( next_arg )
0336             disp( next_arg );
0337             error( 'is not a command string' );
0338         end
0339         
0340         switcher = lower(next_arg);
0341         switch switcher
0342             case 'log' % set the lag flag for log display
0343                 
0344                 counter = counter + 1;
0345                 
0346                 if counter > nargin
0347                     error( 'You need to specify which axes to log scale' );
0348                 end
0349                 next_arg = varargin{counter};
0350                 
0351                 if isnumeric( next_arg ) % if numeic set the ind's to log
0352                     ind = next_arg;
0353                     data.log_flag( ind ) = true;
0354                 else % if there is no numeric ind's turn all to log
0355                     data.log_flag( [1,2] ) = true;
0356                     counter = counter-1;
0357                 end
0358             case 'skip3d'
0359                 data.skip3D_flag = true;
0360                 
0361             case 'drill'
0362                 data.drill_flag = true;
0363                 
0364             case 'err'
0365                 data.error_flag = true;
0366                 
0367                 
0368             case 'line'
0369                 data.line_flag = true;
0370                 data.dot_flag = true;
0371             case 'save'
0372                 data.save_flag = true;
0373                 
0374                 counter  = counter + 1;
0375                 next_arg = varargin{counter};
0376                 
0377                 if counter > nargin
0378                     error( 'Not enough arguments for add' )
0379                 end
0380                 next_arg = varargin{counter};
0381                 if ~ischar( next_arg )
0382                     error( '2nd argument of add must be a str name for the field' );
0383                 end
0384                 
0385                 data.save_name = next_arg;
0386                 
0387             case 'noshow'
0388                 
0389                 data.noshow_flag = true;
0390                 
0391             case 'mult'
0392                 counter = counter + 1;
0393                 if counter > nargin
0394                     error( 'Not enough arguments for MULT.' )
0395                 end
0396                 next_arg = varargin{counter};
0397                 
0398                 if isnumeric( next_arg )
0399                     data.mult = next_arg; 
0400                 end
0401                 
0402             
0403 %             case 'e'
0404 %
0405 %                 counter = counter + 1;
0406 %                 if counter > nargin
0407 %                     error( 'Not enough arguments for target error.' )
0408 %                 end
0409 %                 next_arg = varargin{counter};
0410 %
0411 %                 if isnumeric( next_arg )
0412 %                     data.err = next_arg;
0413 %                 else
0414 %                     error( 'Estimated error must be a double.' );
0415 %                 end
0416                 
0417             case 'newfig'
0418                 data.newfig_flag = true;
0419                 
0420             case 'getgate'
0421                 
0422                 
0423                 counter = counter + 1;                
0424                 if counter > nargin
0425                     error( 'Need to specify which clist.' );
0426                 end
0427                 
0428                 next_arg = varargin{counter};
0429                 if isnumeric( next_arg ) % if numeic set the ind's to log
0430                     data.which_gate = next_arg;
0431                      
0432                      if numel(data.clist) ~= 1 || ~isstruct(data.clist)
0433                         error('Get gate only works with a single clist');
0434                      end
0435                          
0436                      data.get_gate_flag = true;
0437                 else
0438                      error( 'getGate needs a numeric argument .' );
0439                 end
0440                         
0441                 
0442             case 'clear'
0443 
0444                 counter = counter + 1;                
0445                 if counter > nargin
0446                     cind = [];
0447                 else
0448                     cind = [];
0449                     next_arg = varargin{counter};
0450                      if isnumeric( next_arg ) % if numeic set the ind's to log
0451                         cind = next_arg;
0452                         
0453                     else % if there is no numeric ind's t
0454                         counter = counter - 1;      
0455                     end
0456                 end
0457                 
0458                 data.clist = intClear( data.clist, cind );
0459 
0460             case {'xls','csv'}
0461                 counter = counter + 1;
0462                 if counter > nargin
0463                     error( 'Not enough arguments for xls/csv. Must provide filename.' )
0464                 end
0465                 next_arg = varargin{counter};
0466                 if ~ischar( next_arg )
0467                     error( 'You must include a filename.' );
0468                 end
0469                 data.export_filename = next_arg;
0470                 
0471                 data.export_index = [];
0472                 
0473                 counter = counter + 1;
0474                 if counter > nargin || ischar( varargin{counter} )
0475                     counter = counter - 1;
0476                 else
0477                     data.export_index = varargin{counter};
0478                 end
0479                 
0480                 switch switcher
0481                     case 'xls'
0482                         data.which_export_flag = 2;
0483                     case 'csv'
0484                         data.which_export_flag = 1;
0485                 end
0486                         
0487                 data.export_flag = true;
0488                 
0489             case 'save'
0490                 counter = counter + 1;
0491                 if counter > nargin
0492                     error( 'Not enough arguments for save. Must provide filename.' )
0493                 end
0494                 next_arg = varargin{counter};
0495                 if ~ischar( next_arg )
0496                     error( 'You must include a filename.' );
0497                 end
0498                 filename = next_arg;
0499                 
0500                 clist = data.clist;
0501                 
0502                 if isstruct( data.clist )
0503                     save( filename,'-struct','clist' );
0504                 else
0505                     save( filename,'-v7.3','clist' );
0506                 end
0507         
0508            
0509                 
0510             
0511             case 'units'
0512                 counter = counter + 1;
0513                 if counter > nargin
0514                     error( 'Not enough arguments for units. Must provide a scalar or vector.' )
0515                 end
0516                 next_arg = varargin{counter};
0517                 if ~isnumeric( next_arg )
0518                     error( 'units must be scalar or vector.' );
0519                 else
0520                     data.units =  next_arg;   
0521                 end
0522                 
0523                 
0524             case 'add'
0525                 
0526                 if numel( data.clist ) ~= 1
0527                     error( 'You can only add a field to a clist structure, not a cell array' );     
0528                 end
0529                
0530                 counter = counter + 1;
0531                 if counter > nargin
0532                     error( 'Not enough arguments for add' )
0533                 end
0534                 next_arg = varargin{counter};
0535                 if ~isnumeric( next_arg )
0536                     error( '1st argument of add must be the data' );
0537                 end
0538                 
0539                 if numel( next_arg ) ~= size( data.clist.data, 1)
0540                     error( 'added data size must match the clist data dimension' );
0541                 end
0542                 
0543                 ss = size(data.clist.data);
0544                 
0545                 tmp_data = next_arg;
0546                 tmp_data = reshape( tmp_data, [numel(tmp_data),1]);
0547                 
0548                 counter = counter + 1;
0549                 if counter > nargin
0550                     error( 'Not enough arguments for add' )
0551                 end
0552                 next_arg = varargin{counter};
0553                 if ~ischar( next_arg )
0554                     error( '2nd argument of add must be a str name for the field' );
0555                 end
0556                 field_name = next_arg;
0557                 
0558                 data.clist.data = [data.clist.data,tmp_data];
0559                 
0560                 field_name_ = [num2str( size(data.clist.data,2) ),': ',field_name];
0561                 
0562                 data.clist.def{ss(2)+1} = field_name;
0563                 
0564                 disp( ['Adding field ',field_name_] );
0565                 
0566                 
0567             case 'add3d'
0568                 
0569                          
0570                 if numel( data.clist ) ~= 1
0571                     error( 'You can only add a field to a clist structure, not a cell array' );     
0572                 end
0573                
0574                 counter = counter + 1;
0575                 if counter > nargin
0576                     error( 'Not enough arguments for add' )
0577                 end
0578                 next_arg = squeeze(varargin{counter});
0579                 if ~isnumeric( next_arg )
0580                     error( '1st argument of add must be the data' );
0581                 end
0582                 
0583                 if ~all(size( next_arg ) == [size( data.clist.data3D,1),size( data.clist.data3D,3)] )
0584                     error( 'added data size must match the clist data3D dimension' );
0585                 end
0586                 
0587                 tmp_data = next_arg;
0588                 
0589                 ss = size(data.clist.data3D);
0590                  
0591                 counter = counter + 1;
0592                 if counter > nargin
0593                     error( 'Not enough arguments for add' )
0594                 end
0595                 next_arg = varargin{counter};
0596                 if ~ischar( next_arg )
0597                     error( '2nd argument of add must be a str name for the field' );
0598                 end
0599                 field_name = next_arg;
0600                 
0601                 if numel(ss) == 2
0602                     ss(3) = 1;
0603                 end
0604                 
0605                 data.clist.data3D = cat(2,data.clist.data3D,reshape(tmp_data,[ss(1),1,ss(3)]));
0606                 
0607                 field_name_ = [num2str( ss(2)+1 ),': ',field_name];
0608                 
0609                 data.clist.def3D{ss(2)+1} = field_name;
0610                 
0611                 disp( ['Adding field ',field_name_] );
0612                 
0613 
0614             case 'add3dt'               
0615                 data.clist = intDoAddT( data.clist );
0616             case 'trace'
0617                 data.trace_flag = true;
0618                 
0619             case 'get'
0620                 data.get_flag = true;
0621                 
0622                 counter = counter + 1;
0623                 if counter > nargin
0624                     error( 'Not enough arguments for get' )
0625                 end
0626                 next_arg = varargin{counter};
0627                 if ~isnumeric( next_arg )
0628                     error( 'indices must be numeric' );
0629                 end
0630                 
0631                 data.g_ind = next_arg;
0632     
0633                 
0634             case 'def'
0635                 def = intGetDef( data.clist );
0636                 def = intFixDef( def )';
0637                 disp( def );
0638             case 'def3d'
0639                 def = intGetDef3D( data.clist );
0640                 def = intFixDef( def )';
0641                 disp( def );              
0642             case 'merge' % set merge flag
0643                 data.merge_flag = true;
0644             case 'den' % set density flag
0645                 data.den_flag = true;
0646             case 'no clear' % set the names
0647                 data.noclear_flag = true;
0648             case 'kde'
0649                 data.kde_flag = true; 
0650                 
0651             case 'rk' % kernal radius
0652                 counter = counter + 1;
0653                 next_arg = varargin{counter};
0654                 
0655                 if isnumeric( next_arg ) % if numeic set the ind's to log
0656                     data.rk = next_arg;                
0657                 else % if there is no numeric ind's turn all to log
0658                     error( 'KDE kernal radius must be a double' );
0659                 end
0660             case 'rm'              
0661                 counter = counter + 1;
0662                 next_arg = varargin{counter};
0663                 
0664                 if isnumeric( next_arg ) % if numeic set the ind's to log
0665                     data.rm = next_arg;
0666                 else % if there is no numeric ind's turn all to log
0667                     error( 'KDE kernal radius must be a double' );
0668                 end
0669             case 'cond'
0670                 data.cond_flag = true;
0671             case 'inv'
0672                 data.inv_flag = true;
0673             case 'res'
0674                  counter = counter + 1;
0675                 next_arg = varargin{counter};
0676                 
0677                  if isnumeric( next_arg ) % if numeic set the ind's to log
0678                     data.mult = next_arg;
0679 
0680                  else % if there is no numeric ind's turn all to log
0681                     error( 'Resolution must be a double.' );
0682                  end
0683                 
0684             case 'squeeze'
0685                 
0686                 data.clist = intSqueeze( data.clist );
0687                 
0688             case 'expand'
0689                 
0690                 data.clist = intExpand( data.clist );
0691                 
0692             case 'name' % set the names
0693                 
0694                 
0695                 counter = counter + 1;
0696                 next_arg = varargin{counter};
0697                 
0698                 if ~isstr( next_arg )
0699                     error( 'name is not a string' );
0700                 else
0701                     name = next_arg;
0702                     if ~data.array_flag
0703                         data.clist.name = name;
0704                     else
0705                         data.clist = intDoAll( data.clist, 'name', name, data.time_flag);
0706                     end
0707                 end
0708                 
0709             case 'bin'
0710                 data.bin_flag = true;
0711                 
0712                 counter = counter + 1;
0713                 bin     = varargin{counter};
0714                 
0715                 if iscell( bin ) || isnumeric( bin )
0716                     data.bin = bin;
0717                 else
0718                     error( 'Bin must be numeric ar a cell.' );
0719                 end
0720                 
0721             case {'make','gate'}
0722                 counter  = counter + 1;
0723                 if counter > nargin
0724                     error( 'Not enough arguments for add' )
0725                 end
0726                 next_arg = varargin{counter};
0727                 
0728                 if isnumeric( next_arg )
0729                     
0730                     data.ind = next_arg;
0731                     
0732                     counter  = counter + 1;
0733                     if ~(counter > nargin)
0734                         next_arg = varargin{counter};
0735                         if isnumeric( next_arg )
0736                             
0737                             tmp_gate.ind = data.ind;
0738                             
0739                             if numel( data.ind ) == 1
0740                                 tmp_gate.x =  next_arg;
0741                             elseif  numel( data.ind ) == 2
0742                                 tmp_gate.xx =  next_arg;
0743                             end
0744                             
0745                             data = intMakeGate( data, tmp_gate );
0746                             
0747                         else
0748                             data.make_flag = true;
0749                             counter  = counter - 1;
0750                         end
0751                     else
0752                         data.make_flag = true;
0753                     end
0754                 elseif isstruct( next_arg )
0755                     data = intMakeGate( data, next_arg );
0756                 else
0757                     error( 'gate must be numeric ind list or struct' );
0758                 end
0759                 
0760             case {'make3d','gate3d'}
0761                 
0762                 counter  = counter + 1;
0763                 next_arg = varargin{counter};
0764                 
0765                 data.time_flag = true;
0766                 
0767                 if isnumeric( next_arg )
0768                     data.make_flag = true;
0769                     data.ind = next_arg;
0770                     
0771                 elseif isstruct( next_arg )
0772                     data = intMakeGate( data, next_arg );
0773                 else
0774                     error( 'gate must be numeric ind list or struct' );
0775                 end
0776                 
0777             case {'time','3d' }
0778                 
0779                 data.time_flag = true;
0780                 
0781             case 'show'
0782                 data.show_flag = true;
0783                 
0784                 counter  = counter + 1;
0785                 
0786                 if (counter <= nargin) && isnumeric( varargin{counter} )
0787                     data.ind =  varargin{counter};
0788                 else
0789                     data.show_all_flag = true;
0790                     counter  = counter - 1;
0791                 end
0792                 
0793             case 'hist'
0794                 
0795                 data.hist_flag = true;
0796                 
0797             case 'stat'
0798                 data.stat_flag = true;
0799                 
0800              case 'dothist'
0801                 
0802                 data.dothist_flag = true;
0803                     
0804             case 'dot'
0805                 
0806                 data.dot_flag = true;
0807                 
0808             case 'strip'
0809                 
0810                 data.strip_flag = true;
0811                 
0812             case 'color'
0813                 
0814                 counter  = counter + 1;
0815                 color = varargin{counter};
0816                 
0817                 if ~data.array_flag
0818                     data.clist.color = color;
0819                 else
0820                     data.clist = intDoAll( data.clist, 'color', color, data.time_flag);
0821                 end
0822             case ''
0823                 % this is just an empty
0824             otherwise
0825                 disp( [next_arg, ' is not a command'] );
0826                 
0827         end
0828         
0829     end
0830     
0831   
0832 end
0833 
0834  if numel( data.ind ) == 2
0835     data.stat_flag = false; 
0836  end
0837  
0838      
0839 if ~data.hist_flag && ~data.kde_flag && ~data.dot_flag
0840     
0841     if (numel( data.ind ) == 2)
0842         if data.time_flag
0843             data.kde_flag = true;
0844         else
0845             data.dot_flag = true;
0846         end
0847         if numel( data.ind ) == 1
0848             data.hist_flag = true;
0849         end
0850         
0851     end
0852     
0853     
0854 end
0855 
0856 if numel( data.bin ) == 1 && numel( data.ind ) == 2
0857     error( 'Dimension of bin must match ind.' );
0858 end
0859 
0860 end
0861 
0862 %% run gate too  on all clists in a clist
0863 function clist = intDoAll( clist, comm_, arg_, time_flag )
0864 
0865 if ~exist( 'arg_', 'var' )
0866     arg_ = '';
0867 end
0868 
0869 if iscell( clist )
0870     nc = numel( clist );
0871     for ii = 1:nc
0872         if time_flag
0873             clist{ii} = gateTool( clist{ii}, comm_, arg_, 'noshow', '3d' );
0874         else
0875             clist{ii} = gateTool( clist{ii}, comm_, arg_, 'noshow' );
0876         end
0877     end
0878 elseif isstruct( clist )
0879        if time_flag
0880             clist = gateTool( clist, comm_, arg_, 'noshow', '3d' );
0881         else
0882             clist = gateTool( clist, comm_, arg_, 'noshow' );
0883         end          
0884 end
0885 
0886 end
0887 
0888 
0889 
0890 %% Strip out data not used.
0891 function data = intDoStrip( data )
0892 
0893 if data.array_flag
0894     data.clist = intDoAll( data.clist, 'strip', '', data.time_flag );
0895 else
0896     clist  = data.clist;
0897     clist0 = clist;
0898     
0899     % strip out stuff we don't need
0900     if isfield( clist0, 'gate' );
0901         clist0 = rmfield( clist0, {'gate'} );
0902     end
0903     if isfield( clist0, 'idExclude' );
0904         clist0 = rmfield( clist0, {'idExclude'} );
0905     end
0906     if isfield( clist0, 'idExclude' );
0907         clist0 = rmfield( clist0, {'idExclude'} );
0908     end
0909     
0910     
0911     ss = size(clist.data);
0912     inflag = true(ss(1),1);
0913     
0914     if isfield( clist, 'idExclude' ) && ~isempty(clist.idExclude)
0915         inflag = ~ismember(clist.data(:,1), clist.idExclude);
0916     end
0917     
0918     if isfield( clist, 'idInclude' ) && ~isempty(clist.idInclude)
0919         inflag = ismember(clist.data(:,1), clist.idInclude);
0920     end
0921     
0922     if isfield( clist, 'gate' ) && ~isempty ('gate.clist')
0923         for ii = 1:numel(clist.gate)
0924             if numel(clist.gate(ii).ind) == 2
0925                 inflag = and(inflag, inpolygon( clist.data(:,clist.gate(ii).ind(1)), ...
0926                     clist.data(:,clist.gate(ii).ind(2)), ...
0927                     clist.gate(ii).xx(:,1), clist.gate(ii).xx(:,2) ));
0928             else
0929                 x = clist.data(:,clist.gate(ii).ind);
0930                 xg = clist.gate(ii).x;
0931                 
0932                 if numel(xg)==1
0933                     inflag =  and( inflag, xg==x ); 
0934                 else
0935                     inflag = and( inflag, and( x > min(xg), x < max(xg)));
0936                 end
0937             end
0938         end
0939     end
0940     
0941     
0942     clist0.data = clist.data(inflag,:);
0943     if isfield(clist,'data3D') && isfield(clist,'def3D') && ~data.skip3D_flag
0944         clist0.def3D = clist.def3D;
0945         clist0.data3D = clist.data3D(inflag,:,:);
0946     end
0947     
0948     data.clist = clist0;
0949     
0950     if numel(clist0.data) == 0
0951        disp( 'Warning: At least one clist is empty after gating.' ); 
0952     end
0953 end
0954 
0955 end
0956 
0957 %% Add another gate. Interactive if info is not specified at the command line
0958 function data = intMakeGate( data, arg_ )
0959 
0960 clist0 = data.clist;
0961 
0962 % if you pass the gate structure whole just put it in the field
0963 if isstruct(arg_)
0964     
0965     ind = arg_.ind;
0966     
0967     if iscell( data.clist )
0968         data.clist = intDoAll( data.clist, 'make', arg_, data.time_flag );        
0969     else
0970         if ~data.time_flag
0971             if isfield( data.clist, 'gate' ) && ~isempty( data.clist.gate )
0972                 data.clist.gate = intMergeStruct(data.clist.gate,arg_);
0973             else
0974                 data.clist.gate = arg_;
0975             end
0976         else
0977             if isfield( data.clist, 'gate3D' ) && ~isempty( data.clist.gate3D )
0978                 data.clist.gate3D = intMergeStruct(data.clist.gate3D,arg_);
0979             else
0980                 data.clist.gate3D = arg_;
0981             end
0982         end
0983     end 
0984 elseif isnumeric( arg_ ) % fire up the gui and do it by hand
0985     intShow( data );
0986     hold on;
0987     
0988     ylim_ = ylim;
0989     
0990     % 1D get choose min and max
0991     if numel( data.ind ) == 1
0992         disp( 'Click on the max and min value to make a gate.');
0993         for i = 1:2
0994             try
0995                 tmp = ginput(1);
0996             catch
0997                 % if window was closed - does not make any clist
0998                 return;
0999             end
1000             if ~isempty(tmp)
1001                 gxx(i,:) = tmp;
1002                 plot( gxx(i,1)+[0,0], ylim_, 'r--' );
1003             end
1004         end
1005         
1006         ind = data.ind;
1007         tmp_gate.x    = gxx(:,1);
1008         tmp_gate.ind  = data.ind;
1009         tmp_gate.xx   = [];
1010         
1011         % print the gate info to the command window.
1012         if data.time_flag
1013             def = intGetDef3D( data.clist );
1014             disp( ['Gate selected for ', def{data.ind}] );
1015         else
1016             def = intGetDef( data.clist );
1017             disp( ['Gate selected for ', def{data.ind}] );
1018         end
1019         
1020         disp(tmp_gate.x);
1021         
1022         hold on;
1023         plot( gxx(1)+[0,0], ylim_, 'r--' );
1024         hold on;
1025         plot( gxx(2)+[0,0], ylim_, 'r--' );
1026         % Do 2 D gating
1027     elseif numel( data.ind ) == 2
1028         
1029         % do polygon gate
1030         c_flag = 1;
1031         disp('Draw polygon. Finish by pressing return' );
1032         i = 0;
1033         xx = zeros( 100, 2 );
1034         
1035         while c_flag;
1036             dvar = 0;
1037             
1038             i = i+1;
1039             tmp = ginput(1);
1040             if isempty(tmp)
1041                 if i ~= 1
1042                     plot( xx([i-1,1],1), xx([i-1,1],2), 'r-' );
1043                 end
1044                 
1045                 c_flag = false;
1046                 numvert = i-1;
1047             else
1048                 dr = (xx(1,:)-tmp );
1049                 if (i>1) && (sum((dr.^2)) < dvar*0.001 )
1050                     numvert = i-1;
1051                     c_flag = false;
1052                     plot( xx([1,numvert],1), xx([1,numvert],2), 'r-' );
1053                 else
1054                     xx(i,:) = tmp;
1055                     
1056                     if i == 1
1057                         plot( xx(1,1), xx(1,2), 'r-' );
1058                     else
1059                         plot( xx([i,i-1],1), xx([i,i-1],2), 'r-' );
1060                     end
1061                 end
1062             end
1063         end
1064         
1065         xx = xx(1:numvert,:);
1066         
1067         tmp_gate.ind = data.ind;
1068         tmp_gate.xx  = xx;
1069         tmp_gate.x   = [];
1070         
1071         % print the gate info to the command window.
1072         if data.time_flag
1073             def = intGetDef3D( data.clist );
1074             disp( ['Gate selected for ', def{data.ind(1)},', ',def{data.ind(2)}] );
1075         else
1076             def = intGetDef( data.clist );
1077             disp( ['Gate selected for ', def{data.ind(1)},', ',def{data.ind(2)}] );
1078         end
1079         disp( tmp_gate.xx );
1080         
1081     else
1082         error( 'Too many ind to gate. Must be either 1 or 2.' );
1083     end
1084     
1085     % copy the gate in
1086     if ~data.time_flag
1087         data.clist = gateTool( data.clist, 'make', tmp_gate, 'noshow' );
1088         
1089     else
1090         data.clist = gateTool( data.clist, 'make', tmp_gate, 'noshow', '3d' );
1091        
1092     end
1093     
1094     
1095     
1096 else
1097     error( 'Make gate in must be gate structure of indices' );
1098 end
1099 
1100 % if the noshow flag isn't set, show the gate
1101 if ~data.noshow_flag
1102     tmp_clist = data.clist;
1103     
1104     if data.time_flag
1105         gates = intDrillForGate3D(tmp_clist);
1106         intShowGate( clist0, gates(end), numel(gates), data.time_flag );        
1107     else
1108         gates = intDrillForGate(tmp_clist);
1109         intShowGate( clist0, gates(end), numel(gates), data.time_flag );
1110     end
1111 end
1112 
1113 end
1114 
1115 %%
1116 function gate_ = intDrillForGate( clist )
1117     if iscell( clist )
1118         gate_ = intDrillForGate( clist{1} );
1119     elseif isstruct( clist )
1120         gate_ = clist(1).gate;
1121     else
1122         error( 'clist type not expected' );
1123     end
1124 end
1125         
1126 function gate_ = intDrillForGate3D( clist )
1127 if iscell( clist )
1128         gate_ = intDrillForGate( clist{1} );
1129     elseif isstruct( clist )
1130         gate_ = clist(1).gate3D;
1131     else
1132         error( 'clist type not expected' );
1133     end
1134 end
1135 
1136 %% Show the gates if the show flag is true
1137 function [clist, fignum] = intShowAll( clist, fignum, data )
1138 
1139 if ~exist( 'fignum', 'var' )
1140     fignum = 1;
1141 end
1142 
1143 
1144 
1145 clist0 = clist;
1146 
1147 clist0 = gateTool( clist, 'clear' );
1148 gates  = intDrillForGate( clist );
1149 ng = numel( gates );
1150 
1151 for ii = 1:ng
1152     
1153     fignum = fignum + 1;
1154     
1155     figure(fignum);
1156     clf;
1157     
1158     
1159     [N,N0] = intShowGate( clist0, gates(ii), ii, data.time_flag );
1160     
1161     
1162     data.N(ii)  = N;
1163     data.N0(ii) = N0;
1164     
1165     %clist.gate(ii).N = N;
1166     %clist.gate(ii).N0 = N0;
1167     clist0 = gateTool( clist0, 'gate', gates(ii), 'noshow' );
1168 end
1169 
1170 end
1171 
1172 %% get the number of gate and ungated cells...not used.
1173 function [out] = intGetCellNum( clist )
1174 clist = gateTool( clist, 'merge', 'skip3D' );
1175 
1176 num = size( clist.data, 1 );
1177 
1178 clist = gateTool( clist, 'strip', 'skip3D' );
1179 
1180 numG = size( clist.data, 1 );
1181 
1182 out = [numG,num];
1183 end
1184 
1185 
1186 %% Show the gate info on the plot
1187 function [N,N0] = intShowGate( clist, gate_var, gate_num, time_flag )
1188 
1189 if ~exist( 'gate_num', 'var' )
1190     gate_num = 0;
1191 end
1192 
1193 
1194 if time_flag
1195     tmp = gateTool( clist, 'strip', 'merge' );
1196     N0  = size( tmp.data3D, 1);
1197     tmp = gateTool( tmp, 'gate', gate_var, 'noshow', '3d','strip'  );
1198     N   = size( tmp.data3D, 1);
1199     
1200     gateTool( clist, 'show', gate_var.ind, '3d' );
1201 else
1202     tmp = gateTool( clist, 'strip', 'merge', 'skip3d' );
1203     N0  = size( tmp.data, 1);
1204     tmp = gateTool( tmp, 'gate', gate_var, 'noshow', 'skip3d','strip' );
1205     N   = size( tmp.data, 1);
1206     
1207     gateTool( clist, 'show', gate_var.ind );
1208 end
1209 
1210 
1211 
1212 
1213         
1214 hold on;
1215 if numel(gate_var.ind)==1
1216     ylim_ = ylim;
1217     
1218     plot( gate_var.x(1)+0*ylim_,ylim_, '.--', 'color','r' );
1219     if numel( gate_var.x )>1
1220         plot( gate_var.x(2)+0*ylim_,ylim_, '.--', 'color','r' );
1221     end
1222 else
1223     plot( gate_var.xx([1:end,1],1), gate_var.xx([1:end,1],2), '.--', 'color', 'r' );
1224 end
1225 
1226 name = '';
1227 
1228 if isfield( clist, 'name' )
1229     name = clist.name;
1230 end
1231 
1232 title( [name,' Gate: ',num2str(gate_num), ' Cell count: ',num2str(N), ' / ', num2str( N0 )] ); 
1233 
1234 
1235 end
1236 
1237 %% function that handles the data display
1238 function  data0 = intShow( data0 )
1239 
1240 data0.stat = [];
1241 
1242 if ~data0.noclear_flag
1243     clf;
1244 end
1245 
1246 data = data0;
1247 
1248 if data.time_flag
1249     data.clist = gateTool( data.clist, 'strip', 'time' );
1250 else
1251     data.clist = gateTool( data.clist, 'strip', 'skip3D' );
1252 end
1253 
1254 
1255 % make bins
1256 if data0.hist_flag || (numel( data0.ind )==1) || data0.kde_flag
1257     data1 = data;
1258     data1.clist = intDoMerge( data1.clist, [], ~data.time_flag );
1259     
1260     data.binS = intMakeBins( data1.clist, data1  );
1261 end
1262 
1263 % Int show function: Take care of all top level operations
1264 data = intIntShow( data.clist, data );
1265 
1266 nf = max( [1, numel( data.fig_ptr )] );
1267 
1268 for jj = 1:nf
1269     
1270     if ~isempty( data.fig_ptr )
1271         figure( data.fig_ptr(jj) );
1272     end
1273     
1274     if (numel( data.ind ) == 2) && ...
1275             (~data.dot_flag)
1276         
1277         
1278         xx1 = data.xx{1};
1279         xx2 = data.xx{2};
1280         
1281         if data.log_flag(2)
1282             xx1 = exp(xx1);
1283         end
1284         if data.log_flag(1)
1285             xx2 = exp(xx2);
1286         end
1287         
1288         if size(data.clist,2)>1 && ~data.newfig_flag
1289             if ~data.log_flag(3)
1290                 data.im = data.im/max(data.im(:));
1291             end
1292             if data.inv_flag
1293                 data.im = 1-data.im;
1294             end
1295         end
1296         
1297         if data.log_flag(1) 
1298             xx2 = log10(xx2);
1299         end
1300         
1301         if data.log_flag(2) 
1302             xx1 = log10(xx1);
1303         end
1304         
1305         if iscell( data.im )
1306             im = data.im{jj};
1307         else
1308             im = data.im;
1309         end
1310         
1311          imagesc( xx2, xx1, im );
1312         
1313         
1314         
1315         hold on;
1316         
1317         if size(data.clist,2)==1 || data.newfig_flag
1318           intFixColorBar(im);
1319         end
1320         
1321         
1322         axis( [xx2(1),xx2(end),xx1(1),xx1(end)] );
1323         set(gca,'layer','top')
1324     end
1325     
1326     
1327     % set the scale on the axes
1328     if data.log_flag(1)
1329          if (numel(data.ind)==1) || ~( data.kde_flag || data.hist_flag )
1330             set(gca,'XScale','log' );
1331          end
1332     end
1333     
1334     if data.log_flag(2)
1335         if (numel(data.ind)==1) || ~( data.kde_flag || data.hist_flag )
1336             set(gca,'YScale','log' );
1337         end
1338     end
1339     
1340     % set the labels on the axis.
1341     def = intGetDef( data.clist );
1342     def3D = intGetDef3D( data.clist );
1343     
1344     if data.time_flag
1345         labs = def3D(data.ind);
1346     else
1347         labs = def(data.ind);
1348     end
1349     
1350     
1351     if (numel(data.ind)==2) && ( data.kde_flag || data.hist_flag )
1352        if data.log_flag(1)
1353            labs{1} = [labs{1},' (log10)']; 
1354        end
1355        
1356        if data.log_flag(2)
1357            labs{2} = [labs{2},' (log10)']; 
1358        end
1359         
1360     end
1361     
1362     
1363     if data.trace_flag
1364         xlabel( 'Time (Frames)', 'Interpreter','none' );
1365         
1366         
1367         ylabel(  labs{1}, 'Interpreter','none' );
1368     else
1369         if numel( data.ind )
1370             xlabel( labs{1}, 'Interpreter','none'  );
1371         end
1372         
1373         if numel( data.ind ) == 2
1374             ylabel(  labs{2} , 'Interpreter','none');
1375         elseif data.den_flag
1376             ylabel( 'Density', 'Interpreter','none' );
1377         else
1378             ylabel( 'Number' , 'Interpreter','none');
1379         end
1380     end
1381     
1382     set( gca, 'Box', 'on' );
1383     
1384     if ~data.newfig_flag
1385         legend( data.h, data.legend );
1386     end
1387     
1388     set( gca, 'YDir', 'normal' );
1389     
1390 end
1391 
1392 if data.dot_flag || (numel(data.ind)==1)
1393     xlim_ = xlim;
1394     XM = mean(xlim_);
1395     xlim( XM+1.05*(xlim_-XM) );
1396 end
1397 
1398 
1399 if data.stat_flag
1400     figure;
1401     intDoBoxIt( data );
1402 end
1403 
1404 data0.stat = data.stat;
1405 
1406 end
1407 
1408 function intFixColorBar( im )
1409 try
1410 colorbar
1411 
1412 cc = colormap;
1413 cc(1,:) = [0.5,0.5,0.5];
1414 colormap(cc);
1415 
1416 tmp = im;
1417 tmp(tmp==0) = nan;
1418 min_caxis = min(tmp(:));
1419 max_caxis = max(tmp(:));
1420 
1421 N = size(cc,1);
1422 c = (N*min_caxis-max_caxis)/(N-1);
1423 if ~isnan( max_caxis )
1424     caxis( [c,max_caxis] );
1425 end
1426 
1427 end
1428 end
1429 %%
1430 % function intDoBoxIt( stat, h )
1431 %
1432 % ns = numel( stat );
1433 % zz = [0,0];
1434 %
1435 % for ii = 1:ns
1436 %
1437 %     plot( ii + zz, [stat(ii).min,stat(ii).max], ':', 'color', 'b' ),
1438 %     hold on;
1439 %     plot( ii + zz, stat(ii).mean+stat(ii).std*[-1,1], '-', 'color', 'b' ),
1440 %     plot( ii + zz, stat(ii).mean+stat(ii).err*[-1,1], '-', 'color', 'b', 'LineWidth', 2 ),
1441 % end
1442 %
1443 %
1444 %
1445 % end
1446 
1447 
1448 function intDoBoxIt( data )
1449 
1450 sort_flag = true;
1451 cc = 'k';
1452 
1453 stat = data.stat;
1454 ns = numel( stat );
1455 
1456 if sort_flag
1457     mean_data = [data.stat(:).mean];
1458     [~,ord] = sort(  mean_data );
1459 else
1460     ord = 1:ns;
1461 end
1462 
1463 zz = [0,0];
1464 
1465 px = [];
1466 for jj = 1:ns
1467     
1468     ii = ord(jj);
1469     px = [px,data.stat(ii).px'];
1470 end
1471 xx = data.stat(1).xx;
1472 
1473 % if data.log_flag(1)
1474 %     xx = log10( xx );
1475 % end
1476 
1477 
1478 bin = 1:ns;
1479 
1480 % if data.log_flag(2)
1481 %      px = log(px);
1482 % end
1483 
1484 
1485 if data.log_flag(1)
1486     imagesc( bin, log10(xx), px );
1487 else
1488     imagesc( bin, xx, px );
1489 end
1490 
1491 hold on;
1492 
1493 names = {};
1494 
1495 for jj = 1:ns
1496     
1497     ii = ord(jj);
1498     
1499     yy1 = [stat(ii).min,stat(ii).max];
1500     yy2 = stat(ii).mean+stat(ii).std*[-1,1];
1501     yy3 = stat(ii).mean+stat(ii).err*[-1,1];
1502     yy4 =  stat(ii).mean;
1503     
1504 %     if data.log_flag(1)
1505 %         yy1 = log10( yy1 );
1506 %         yy2 = log10( yy2 );
1507 %         yy3 = log10( yy3 );
1508 %         yy4 = log10( yy4 );
1509 %     end
1510 if data.log_flag(1)
1511     plot( jj + zz, log10(yy1), ':', 'color', cc ),
1512     plot( jj + zz, log10(yy2), '-', 'color', cc ),
1513     plot( jj + zz, log10(yy3), '-', 'color', cc, 'LineWidth', 2 ),
1514     plot( jj     , log10(yy4), '.', 'color', cc, 'MarkerSize', 10 ),
1515 else   
1516     plot( jj + zz, yy1, ':', 'color', cc ),
1517     plot( jj + zz, yy2, '-', 'color', cc ),
1518     plot( jj + zz, yy3, '-', 'color', cc, 'LineWidth', 2 ),
1519     plot( jj     , yy4, '.', 'color', cc, 'MarkerSize', 10 ),
1520 end
1521     name_tmp  = stat(ii).name;
1522     ind = find(name_tmp == '(',1,'last');
1523     names{jj} = name_tmp(1:ind-2);
1524     
1525 end
1526 
1527 
1528 intFixColorBar(px)
1529 
1530 %names = {stat(ord).name};
1531 set( gca, 'Xtick', [1:ns],'XTickLabels',names );
1532 set( gca, 'XTickLabelRotation', 45 )
1533 set( gca, 'YDir', 'normal' );
1534 
1535 % xlim_ = xlim;
1536 % XM = mean(xlim_);
1537 % xlim( XM+1.05*(xlim_-XM) );
1538 
1539 
1540 def = intGetDef( data.clist );
1541 def3D = intGetDef3D( data.clist );
1542 
1543 
1544 if data.time_flag
1545     labs = def3D(data.ind);
1546 else
1547     labs = def(data.ind);
1548 end
1549 
1550 if (numel(data.ind)==2) && ( data.kde_flag || data.hist_flag )
1551     if data.log_flag(1)
1552         labs{1} = [labs{1},' (log10)'];
1553     end
1554 end
1555 
1556 tmp = labs{1};
1557 if data.log_flag(1)
1558 tmp = ['log ', tmp ];
1559 end
1560 ylabel(tmp, 'Interpreter','none'  );
1561 
1562 
1563 
1564 
1565 end
1566 
1567 
1568 %% internal show data fuction
1569 function data = intIntShow( clist, data )
1570 
1571 
1572 if iscell(clist)
1573     
1574     nc = size( clist,2 );
1575     nr = size( clist,1 );
1576     
1577     if (nr~=1) && (nc~=1)
1578         error( 'At least one dimension of the clist cell array should be unitary' );
1579     else
1580         if nr > 1
1581             if data.time_flag
1582                 clist = gateTool( clist, 'merge', 'time' );
1583             else
1584                 clist = gateTool( clist, 'merge', 'skip3D' );
1585             end
1586             data = intIntShow( clist, data );
1587         else
1588             for ii = 1:nc
1589                 data = intIntShow( clist{ii}, data );
1590             end
1591         end
1592     end
1593     
1594 else
1595     
1596     [data] = intIntIntShow( clist, data );
1597     hold on;
1598 end
1599 
1600 end
1601 
1602 
1603 %% internal show data fuction
1604 function [data] = intIntIntShow( clist, data )
1605 
1606 stat = [];
1607 
1608 if isfield( clist, 'name' );
1609     name = clist.name;
1610 else
1611     name = ['data ', num2str(numel( data.h )) ];
1612 end
1613 
1614 if data.newfig_flag
1615     data.fig_ptr = [data.fig_ptr, figure()];
1616 end
1617 
1618 switch numel( data.ind )
1619     
1620     case 0
1621         error( 'No indices to show' );
1622     case 1 % 1D
1623         if data.kde_flag
1624             [data,h,stat] = intShowKDE1D(  clist, data, name );
1625         %elseif data.time_flag
1626         %    [data,h] = intTime( clist, data );
1627         else
1628             [data,h,stat] = intShowHist1D( clist, data, name );
1629         end
1630     case 2 % 2D
1631         if data.hist_flag
1632             [data,h] = intShowHist2D( clist, data, name );
1633         elseif data.dot_flag
1634             [data,h] = intShowDot(    clist, data, name );
1635         elseif data.kde_flag
1636             [data,h] = intShowKDE2D(  clist, data, name );
1637         else %default
1638             [data,h] = intShowDot(    clist, data, name );
1639         end
1640 end
1641 
1642 data.h = [data.h,h];
1643 
1644 
1645 
1646 nc = size( clist.data, 1 );
1647 
1648 stat.name0 = name;
1649 
1650 if data.time_flag
1651     name = [name,' (',num2str( data.n, '%1.2g' ),' points)'];
1652 else
1653     name = [name,' (',num2str( nc ),' cells)'];
1654 end
1655 
1656 stat.name = name;
1657    
1658 if data.newfig_flag
1659     legend( h, name );
1660 else
1661     data.legend = {data.legend{:},name};
1662 end
1663 
1664 if isfield( data, 'stat' ) && ~isempty( data.stat )
1665     data.stat = [data.stat,stat];
1666 else
1667     data.stat = [stat];
1668 end
1669 
1670 end
1671 
1672 %% Show 1D histogram
1673 function [data,h,stat] = intShowHist1D( clist, data, name )
1674 
1675 stat = [];
1676 
1677 [x1,x0,flagger,n] = intGetDataC( clist, data,1 );
1678 data.n = n;
1679 
1680 [y,x] = hist( x1, data.binS.xx );
1681 dy    = intDoError(y); 
1682 
1683 if data.den_flag
1684     dx = diff(x(1:2));
1685     %dx = ([dx(1),dx]+[dx,dx(end)])/2;
1686     
1687     normer = 1./(dx*sum(y(:)));
1688     y = y*normer;
1689     dy = dy*normer;
1690 end
1691 
1692 
1693 if data.log_flag(1)
1694     x_plot = exp(x);
1695 else
1696      x_plot = x;
1697 end
1698 
1699 if isfield( clist, 'color' )
1700     cc = clist.color;
1701     h = plot( x_plot,y, '.-', 'color', cc );
1702 else
1703     h = plot( x_plot,y, '.-' );
1704     cc = h.Color;
1705 end
1706 
1707 if data.error_flag
1708     hold on;
1709     plot( x_plot,intFixError(y-dy), ':', 'color', cc );
1710     plot( x_plot,intFixError(y+dy), ':', 'color', cc );
1711 end
1712 
1713 
1714 if ~data.bin_flag
1715     data.bin = x;
1716 end
1717 
1718 if data.stat_flag
1719     stat = intDoStatAn( x0, x_plot, y, n, data, cc, name );
1720 end
1721 
1722 end
1723 
1724 %% Do statistical analysis.
1725 function stat = intDoStatAn( x1, x, y, n, data, cc, name )
1726 
1727    hold on;
1728    
1729    styl = '%1.3e';
1730    
1731    
1732    x1_mean = mean( x1 );
1733    x1_std  = std(  x1 );
1734    x1_max  = max(  x1 );
1735    x1_min  = min(  x1 );
1736    x1_p1   = x1_mean+x1_std;
1737    x1_p1m  = x1_mean+x1_std/sqrt(n);
1738    x1_m1   = x1_mean-x1_std;
1739    x1_m1m  = x1_mean-x1_std/sqrt(n);
1740    
1741    all_out_text = [name,' -- stats: n = ',num2str( n, styl ),', '];
1742    
1743    y1_mean = interp1( x,y, x1_mean );
1744    y1_p1   = interp1( x,y, x1_p1 );
1745    y1_p1m  = interp1( x,y, x1_p1m );
1746    y1_m1   = interp1( x,y, x1_m1 );
1747    y1_m1m  = interp1( x,y, x1_m1m );
1748    y1_max  = interp1( x,y, x1_max ,'linear','extrap');
1749    y1_min  = interp1( x,y, x1_min,'linear','extrap' );
1750    
1751    
1752    stat      = [];
1753    stat.mean = x1_mean;
1754    stat.std  = x1_std;
1755    stat.err  = x1_std/sqrt(n);
1756    stat.px   = y;
1757    stat.xx   = x;
1758    stat.max  = x1_max;
1759    stat.min  = x1_min;
1760    stat.n    = n;
1761    stat.x    = x1;
1762    
1763    if data.log_flag(2)
1764        del = [1e-1,1];
1765    else
1766        del = [0,1];
1767    end
1768    
1769    
1770    plot( x1_mean+[0,0], del*y1_mean, 'x:', 'color', cc, 'MarkerSize', 10 );
1771    
1772    out_text = [' mean: ',num2str( x1_mean, styl )];
1773    text( x1_mean, y1_mean/2, out_text, 'color', cc );
1774    all_out_text = [ all_out_text, out_text,','];
1775    
1776    plot( x1_p1+[0,0], del*y1_p1, 'x:', 'color', cc, 'MarkerSize', 10 );
1777    
1778    out_text = [' std: ',num2str( x1_std, styl )];
1779    text( x1_p1, y1_p1*.75, out_text, 'color', cc );
1780    all_out_text = [ all_out_text, out_text,','];
1781    
1782    plot( x1_m1+[0,0], del*y1_m1, 'x:', 'color', cc, 'MarkerSize', 10 );
1783    
1784    %out_text = [' std: ',num2str( x1_std, styl )];
1785    %text( x1_p1, y1_p1*.75, out_text, 'color', cc );
1786    %all_out_text = [ all_out_text, out_text,','];
1787    
1788    plot( x1_p1m+[0,0], del*y1_p1m, 'x:', 'color', cc, 'MarkerSize', 10 );
1789    plot( x1_m1m+[0,0], del*y1_m1m, 'x:', 'color', cc, 'MarkerSize', 10 );
1790    % plot( x1_max+[0,0], del*y1_max, 'x:', 'color', cc, 'MarkerSize', 10 );
1791    % plot( x1_min+[0,0], del*y1_min, 'x:', 'color', cc, 'MarkerSize', 10 );
1792    
1793    out_text = [' error: ',num2str( x1_std/sqrt(n), styl )];
1794    text( x1_p1m, y1_p1m*.25, out_text, 'color', cc );
1795    all_out_text = [ all_out_text, out_text,','];
1796    
1797    out_text = [' max: ',num2str( x1_std/sqrt(n), styl )];
1798    %text( x1_max, y1_max, out_text, 'color', cc,...
1799    %    'VerticalAlignment', 'baseline');
1800    all_out_text = [ all_out_text, out_text,','];
1801    
1802    out_text = [' min: ',num2str( x1_std/sqrt(n), styl )];
1803    %text( x1_min, y1_min, out_text, 'color', cc,...
1804    %    'HorizontalAlignment', 'right', 'VerticalAlignment', 'baseline');
1805    all_out_text = [ all_out_text, out_text,'.'];
1806    
1807    disp( all_out_text );
1808 end
1809 
1810 
1811 function dy = intDoError( y )
1812 
1813 dy = sqrt( y );
1814 dy(dy<1) = 1;
1815 
1816 end
1817 
1818 function y = intFixError( y )
1819 
1820 y(y<0) = 0;
1821 
1822 end
1823 
1824 %% show 1D kde
1825 function [data,h,stat] = intShowKDE1D( clist, data, name )
1826 
1827 stat = [];
1828 
1829 [x1,x0,flagger,n] = intGetDataC( clist, data, 1 );
1830 data.n = n;
1831 
1832 bin = data.binS(1).xx;
1833 dx  = data.binS(1).dx;
1834 rk  = data.binS(1).rk_pix;
1835 
1836 [y,x] = hist( x1, bin );
1837 
1838 
1839 if data.log_flag(1)
1840     x_plot = exp(x);
1841 else
1842     x_plot = x;
1843 end
1844 
1845 
1846 %[yf,dyf] = intConv1D( y, data, dx );
1847 [yf,dyf] = intConv1Dint( y, rk );
1848 
1849 %dyf =  intDoError( yf );
1850 
1851 if data.den_flag
1852     normer = 1./( sum(y(:))*dx );
1853     yf = yf*normer;
1854     dyf = dyf*normer;
1855 end
1856 
1857 if isfield( clist, 'color' )
1858     cc = clist.color;
1859     h = plot( x_plot,yf, '-', 'color', cc );
1860 else
1861     h = plot( x_plot,yf, '-' );
1862     cc = h.Color;
1863 end
1864 
1865 if data.error_flag
1866     hold on;
1867     plot( x_plot,intFixError(yf-dyf), ':', 'color', cc );
1868     plot( x_plot,intFixError(yf+dyf), ':', 'color', cc );
1869 end
1870 
1871 
1872 if ~data.bin_flag
1873     data.bin = x;
1874 end
1875 
1876 
1877 if data.stat_flag
1878     stat = intDoStatAn( x0, x_plot, yf, n, data, cc, name);
1879 end
1880 
1881 
1882 end
1883 
1884 %% Make the bin sizes if they aren't specified
1885 function binS_vec = intMakeBins( clist, data )
1886 
1887 for ii = 1:numel( data.ind )
1888     if data.kde_flag
1889            num = data.multi;
1890     else
1891        if isfield( data, 'bin' ) && ~isempty( data.bin ) 
1892            num = data.bin(ii);
1893        else
1894            num = intChooseBin(clist, data, ii);
1895        end
1896     end
1897 
1898    binS = intMakeDX( clist, data, num, ii );
1899     
1900     if ~data.kde_flag
1901         binS.rk_pix = [];
1902         binS.rm_pix = [];
1903     else
1904         if isfield( data, 'rk' ) && ~isempty( data.rk )
1905             binS.rk_pix = data.rk(ii)/binS.dx;
1906         else
1907             binS.rk_pix = intChooseRK(clist, data, ii);
1908         end
1909         
1910         if isfield( data, 'rm' ) && ~isempty( data.rm )
1911             binS.rm_pix = data.rm(ii)/binS.dx;
1912         else
1913             binS.rm_pix = binS.rk_pix;
1914         end
1915     end
1916     
1917     binS_vec(ii) = binS;
1918 end
1919 end
1920 
1921 % Make structures for binning the data or determining the kernel radius
1922 function binS = intMakeDX( clist, data, num, ind )
1923 x = intGetData( clist, data, data.ind(ind), data.units(ind) );
1924 if data.log_flag(ind)
1925     x = log(x);
1926 end
1927 x = fixVals( x );
1928 
1929 x_max = max( x(:) );
1930 x_min = min( x(:) );
1931 
1932 if x_max == x_min
1933     tmp = x_max;
1934     x_max = tmp+1;
1935     x_min = tmp-1;
1936 elseif isempty( x_max )
1937     DX = 1;
1938     x_max =  0.5;
1939     x_min = -0.5;
1940 end
1941 
1942 DX = x_max - x_min;
1943 xx = DX*(0:(num-1))/(num-1)+x_min;
1944 dx = xx(2)-xx(1);
1945 
1946 binS.xx    = xx;
1947 binS.dx    = dx;
1948 binS.DX    = DX;
1949 binS.x_max = x_max;
1950 binS.x_min = x_min;
1951 binS.x     = x;
1952 end
1953 
1954 
1955 % find the fundamental resolution of the data.
1956 function dx_min = intFindSmallest( x )
1957 
1958 dx_min = min(diff(sort(unique(x(:)))));
1959 
1960 if isempty( dx_min )
1961     dx_min = 1;
1962 end
1963 
1964 
1965 end
1966 
1967 %% Make automatic choice of bin size.
1968 function num_ = intChooseBin(clist, data, ind)
1969 
1970 del = 2;
1971 
1972 binS = intMakeDX( clist, data, 2, ind );
1973 x    = intGetDataC( clist, data, ind );
1974 
1975 dx_min = intFindSmallest( x );
1976 maxBinNum = min( [floor(binS.DX/dx_min),data.multi]);
1977 
1978 ln_vec = log(data.minBinNum):log(del):log(maxBinNum);
1979 n_vec  = round( exp(ln_vec) );
1980 
1981 num_n = numel(n_vec);
1982 
1983 if num_n == 0
1984     num_ = data.multi;
1985 else
1986     switcher = nan( [1,num_n] );
1987     
1988     for ii = 1:num_n
1989         num  = n_vec(ii);
1990         binS = intMakeDX( clist, data, num, ind );
1991         
1992         y = hist( x, binS.xx );
1993         
1994         if false
1995             delta_y = abs(diff(y));
1996             dy      = sqrt( (y(2:end)+y(1:end-1))/2 );
1997         else
1998             tmp = diff(y);
1999             tmp = tmp([1,1:end,end]);
2000             delta_y = abs(tmp(2:end)+tmp(1:end-1))/2;
2001             dy      = sqrt( y );
2002         end
2003         
2004         %switcher(ii) = mean( delta_y > 2*dy );
2005         switcher(ii) = sum( y.*(delta_y > 2*dy))/sum(y);
2006     end
2007     
2008     
2009     cutt = 0.5;
2010     
2011     ind_n = find( switcher < cutt, 1, 'first' ) - 1;
2012     
2013     if isempty( ind_n ) || ind_n < 1 || ind_n > num_n
2014         if switcher(1) < cutt
2015             ind_n = 1;
2016             num_ = n_vec(ind_n);
2017         elseif switcher(end) > cutt
2018             num_ = maxBinNum;
2019             ind_n = num_n;
2020         end
2021     end
2022     
2023     num_ = n_vec(ind_n);
2024 end
2025 end
2026 
2027 %% Make automatic selection of kernel radius for kde
2028 function rk_pix = intChooseRK(clist, data, ind)
2029 
2030 binS = intMakeDX( clist, data, data.multi, ind );
2031 x    = intGetDataC( clist, data, ind );
2032 
2033 dx_min = intFindSmallest( x );
2034 maxBinNum = min( [(binS.DX/dx_min),data.multi]);
2035 
2036 
2037 ln_vec = log(data.minBinNum):log(1.5):log(maxBinNum);
2038 n_vec  = round( exp(ln_vec) );
2039 rk_vec = data.multi./n_vec;
2040 
2041 num_n = numel(n_vec);
2042 
2043 if num_n == 0
2044     rk_pix = 1;
2045 else
2046     switcher = nan( [1,num_n] );
2047     
2048     for ii = 1:num_n
2049         num  = n_vec(ii);
2050         
2051         y = hist( x, binS.xx );
2052         [y,dy] = intConv1Dint( y, rk_vec(ii) );
2053         
2054         delta_y = rk_vec(ii)*abs(diff(y));
2055         dy      = (dy(1:end-1)+dy(2:end))/2;
2056         y_      = (y(2:end)+y(1:end-1))/2; 
2057         
2058         switcher(ii) =sum( y_.*(delta_y > 2*dy))/sum(y_);
2059     end
2060     
2061     cutt = .5;
2062     
2063     ind_n = find( switcher < cutt, 1, 'first' ) - 1;
2064     
2065     if isempty( ind_n ) || ind_n < 1 || ind_n > num_n
2066         if switcher(1) < cutt
2067             ind_n = 1;
2068         elseif switcher(end) > cutt
2069             ind_n = num_n;
2070         end
2071     end
2072     
2073     rk_pix = rk_vec(ind_n);
2074 end
2075 end
2076 
2077 %% Strip out imaginary, nan and inf values
2078 function [x,flagger] = fixVals( x )
2079 
2080 flagger = ~( isinf( x ) + isnan( x) + imag( x ) );
2081 x = x(flagger);
2082 
2083 end
2084 
2085 %% Make 2D Hist
2086 function [data,h] = intShowHist2D( clist, data, name )
2087 
2088 [x_vec,x0,flagger,n] = intGetDataC( clist, data, [1,2] );
2089 data.n = n;
2090 x1 = x_vec(:,1);
2091 x2 = x_vec(:,2);
2092 
2093 [y,xx] = hist3( [x2,x1], {data.binS(2).xx,data.binS(1).xx} );
2094 
2095 if data.cond_flag
2096    ys = sum( y, 1 );
2097    
2098    ys(ys==0) = 1;
2099    
2100    y = y./(ones([size(y,1),1])*ys);
2101  %  cutt = 1/(2*data.mult);
2102  %  y(y>cutt) = cutt;
2103    
2104 end
2105 
2106 if data.log_flag(3)
2107     y = log(y);
2108     y(isinf(y)) = nan;
2109     y(isnan(y)) = min(y(:));
2110 end
2111 
2112 
2113 hold on;
2114 if isfield( clist, 'color' )
2115     cc = clist.color;
2116     h = plot( nan, nan, '.', 'color', cc);
2117 
2118 else
2119     h = plot( nan, nan, '.');
2120 end
2121 
2122 cc = h.Color;
2123 
2124 if ischar( cc )
2125     cc = convert_color( cc)
2126 end
2127 
2128 
2129 
2130 if (size( data.clist,2 ) > 1) && ~data.newfig_flag    
2131     dd = y/max(y(:));
2132     
2133     im = cat(3, dd*cc(1), dd*cc(2), dd*cc(3) );
2134     
2135     
2136     if isfield( data, 'im' ) && ~isempty( data.im )
2137         data.im = data.im + im;
2138     else
2139         data.im = im;
2140     end
2141     
2142 else
2143     data.im = {data.im{:},y};
2144 end
2145 
2146 data.xx = xx;
2147 
2148 
2149 end
2150 
2151 %% Make 2D KDE
2152 function [data,h] = intShowKDE2D( clist, data, name )
2153 
2154 [x_vec,x0,flagger,n] = intGetDataC( clist, data, [1,2] );
2155 data.n = n;
2156 x1 = x_vec(:,1);
2157 x2 = x_vec(:,2);
2158 
2159 bin = {data.binS(2).xx,data.binS(1).xx};
2160 dx  = [data.binS(2).dx,data.binS(1).dx];
2161 
2162 [y,xx] = hist3( [x2,x1], bin );
2163 
2164 
2165 if data.cond_flag
2166    ys = sum( y, 1 );
2167    
2168    ys(ys==0) = 1;
2169    
2170    y = y./(ones([size(y,1),1])*ys);
2171  %  cutt = 1/(2*data.mult);
2172  %  y(y>cutt) = cutt;
2173    
2174 end
2175 
2176 %y = intConv2Dadd( y, data, dx );
2177 y = intConv2D( y, data );
2178 
2179 if data.den_flag
2180     y = y./sum(y(:));
2181 end
2182 
2183 y = y/prod(dx);
2184 
2185 if data.log_flag(3)
2186     y = log(y);
2187     y(isinf(y)) = nan;
2188     %y(isnan(y)) = min(y(:));
2189 end
2190 
2191 
2192 hold on;
2193 
2194 if isfield( clist, 'color' )
2195     cc = clist.color;
2196     h = plot( nan, nan, '.', 'color', cc);
2197 
2198 else
2199     h = plot( nan, nan, '.');
2200 end
2201 
2202 
2203 cc = h.Color;
2204 
2205 if ischar( cc )
2206     cc = convert_color( cc);
2207 end
2208 
2209 if data.inv_flag
2210    cc = 1-cc; 
2211 end
2212 
2213 if size( data.clist, 2 ) > 1 && ~data.newfig_flag 
2214 
2215     
2216     dd = y/max(y(:));
2217     
2218     im = cat(3, dd*cc(1), dd*cc(2), dd*cc(3) );
2219     
2220     
2221     if isfield( data, 'im' ) && ~isempty( data.im )
2222         data.im = data.im + im;
2223     else
2224         data.im = im;
2225     end
2226     
2227 else
2228     data.im = {data.im{:},y};
2229 end
2230 
2231 data.xx = xx;
2232 data.bin = bin;
2233 
2234 
2235 end
2236 
2237 %% Do gaussian convolution in 2D for KDE
2238 function [yf] = intConv2D( y, data )
2239 
2240 rk = [data.binS(1).rk_pix,data.binS(2).rk_pix];
2241 rm = [data.binS(1).rm_pix,data.binS(2).rm_pix];
2242 
2243 
2244 
2245 xx = -ceil(1.1*rm(1)):ceil(1.1*rm(1));
2246 yy = -ceil(1.1*rm(2)):ceil(1.1*rm(2));
2247 [X,Y] = meshgrid( xx,yy);
2248 R = sqrt((X./rm(1)).^2+(Y./rm(2)).^2);
2249 fdisk = double( R<=1 );
2250 
2251 %fdisk = fspecial( 'disk', rm  );
2252 
2253 xx = -ceil(7*rk(1)):ceil(7*rk(1));
2254 yy = -ceil(7*rk(2)):ceil(7*rk(2));
2255 [X,Y] = meshgrid( xx,yy);
2256 R = sqrt((X./rk(1)).^2+(Y./rk(2)).^2);
2257 
2258 fgaus = exp( -R.^2/2 )/(2*pi*rk(1)*rk(2));
2259 
2260 minner = imfilter( y, fdisk, 0 );
2261 
2262 yf      = imfilter( y, fgaus, 0 );
2263 
2264 %yf = max( yf, minner );
2265 
2266 yf( minner==0) = 0;
2267 yf = yf;
2268 
2269 end
2270 
2271 %% Internal KDE convolution function
2272 function [yf,dyf] = intConv1Dint( y, rk )
2273 
2274 xx = -ceil(7*rk(1)):ceil(7*rk(1));
2275 R = sqrt((xx./rk(1)).^2);
2276 
2277 fgaus = exp( -R.^2/2 )/sqrt(2*pi*rk(1)^2);
2278 
2279 yf      = imfilter( y, fgaus, 0 );
2280 dyf     = sqrt(imfilter( y, fgaus.^2, 0 ));
2281 
2282 end
2283 
2284 function [yf,dyf] = intConv1D( y, data, dx )
2285 
2286 if isempty( data.rk )
2287     [yf,dyf,rk] = intConv1Dadd( y, data, dx );
2288 else
2289     rk = data.rk./dx;
2290     
2291     
2292     
2293     xx = -ceil(7*rk(1)):ceil(7*rk(1));
2294     R = sqrt((xx./rk(1)).^2);
2295     
2296     fgaus = exp( -R.^2/2 )/sqrt(2*pi*rk(1)^2);
2297     
2298     yf      = imfilter( y, fgaus, 0 );
2299     dyf     = sqrt(imfilter( y, fgaus.^2, 0 ));
2300     
2301     %yf = max( yf, minner );
2302     
2303 end
2304 
2305 end
2306 
2307 %% Show do plot in 2D
2308 function [data,h] = intShowDot( clist, data, name )
2309 
2310     hold on;
2311 
2312     
2313 if ~data.time_flag
2314     x1 = intGetData( clist, data, data.ind(1), data.units(1) );
2315     x2 = intGetData( clist, data, data.ind(2), data.units(2) );
2316 
2317     
2318     if isfield( clist, 'color' )
2319         h = scatter( x1, x2, [], clist.color, '.' );
2320     else
2321         h = scatter( x1, x2, '.' );
2322     end
2323 else
2324     x1 = squeeze(clist.data3D(:,data.ind(1),:));
2325     x2 = squeeze(clist.data3D(:,data.ind(2),:));
2326     
2327     [~,flagger] = fixVals( x1 + x2 );
2328     data.n = sum( flagger(:) );
2329     n   = data.n;
2330     
2331     if isfield( clist, 'color' )
2332         cc = clist.color;
2333         h = plot( nan,nan, '.', 'color', cc );
2334     else
2335         h = plot( nan,nan, '.' );
2336         cc = h.Color;
2337     end
2338    
2339     if ischar( cc )
2340         cc = convert_color(cc);
2341     end
2342     
2343     nc = size( x1, 1 );
2344     
2345     for ii = 1:nc
2346         
2347         hh = plot( nan, nan, '.' );
2348         cc_ii = hh.Color;
2349         cc_ii = (cc_ii+cc)/2;
2350         
2351         if data.line_flag
2352             plot( x1(ii,:), x2(ii,:), 'color', cc_ii );
2353             
2354             start_ind = find( ~isnan( x1(ii,:)+x2(ii,:) ), 1, 'first' );
2355             end_ind   = find( ~isnan( x1(ii,:)+x2(ii,:) ), 1, 'last' );
2356             
2357             plot( x1(ii,start_ind), x2(ii,start_ind), '.','MarkerSize', 10, 'color', cc_ii );
2358             plot( x1(ii,end_ind), x2(ii,end_ind  ), '.','MarkerSize', 10, 'color', cc_ii );
2359         else
2360             plot( x1(ii,:), x2(ii,:), '.', 'color', cc_ii );           
2361         end
2362     end
2363     
2364 end
2365 
2366 
2367 end
2368 
2369 %% Get field definition from the structure
2370 function def = intGetDef( clist )
2371 
2372 if isstruct( clist )
2373     def = clist.def;
2374 elseif iscell( clist )
2375     def = intGetDef( clist{1} );
2376     %def = intFixDef( def );
2377 else
2378     error( 'empty clist in intGetDef' );
2379 end
2380 
2381 
2382 end
2383 
2384 function def = intFixDef( def )
2385 
2386 if ~isempty( def )
2387     
2388     nd = numel( def );
2389     for ii = 1:nd
2390         def{ii} = [num2str(ii),' : ',def{ii}];
2391     end
2392     
2393     def = {'Index : Descriptor', def{:} };
2394     
2395 end
2396 
2397 end
2398 
2399 %% Get 3D field definition from the structure
2400 function def = intGetDef3D( clist );
2401 
2402 if isstruct( clist )
2403     if isfield( clist, 'def3D' )
2404         def = clist.def3D;
2405     elseif isfield( clist, 'def3d' )
2406         def = clist.def3d;
2407         %def = intFixDef( def );
2408     else
2409         def = {};
2410     end
2411 elseif iscell( clist )
2412     def = intGetDef3D( clist{1} );
2413 else
2414     error( 'empty clist in intGetDef' );
2415 end
2416 
2417 
2418 end
2419 
2420 %% Fix colors. From internet.
2421 function outColor = convert_color(inColor)
2422 
2423 charValues = 'rgbcmywk'.';  %#'
2424 rgbValues = [eye(3); 1-eye(3); 1 1 1; 0 0 0];
2425 assert(~isempty(inColor),'convert_color:badInputSize',...
2426     'Input argument must not be empty.');
2427 
2428 if ischar(inColor)  %# Input is a character string
2429     
2430     [isColor,colorIndex] = ismember(inColor(:),charValues);
2431     assert(all(isColor),'convert_color:badInputContents',...
2432         'String input can only contain the characters ''rgbcmywk''.');
2433     outColor = rgbValues(colorIndex,:);
2434     
2435 elseif isnumeric(inColor) || islogical(inColor)  %# Input is a numeric or
2436     %#   logical array
2437     assert(size(inColor,2) == 3,'convert_color:badInputSize',...
2438         'Numeric input must be an N-by-3 matrix');
2439     inColor = double(inColor);           %# Convert input to type double
2440     scaleIndex = max(inColor,[],2) > 1;  %# Find rows with values > 1
2441     inColor(scaleIndex,:) = inColor(scaleIndex,:)./255;  %# Scale by 255
2442     [isColor,colorIndex] = ismember(inColor,rgbValues,'rows');
2443     assert(all(isColor),'convert_color:badInputContents',...
2444         'RGB input must define one of the colors ''rgbcmywk''.');
2445     outColor = charValues(colorIndex(:));
2446     
2447 else  %# Input is an invalid type
2448     
2449     error('convert_color:badInputType',...
2450         'Input must be a character or numeric array.');
2451     
2452 end
2453 end
2454 
2455 
2456 %% intDoMerge merges clists into a single list
2457 function clistM = intDoMerge( clist, ID_ind, skip3D )
2458 
2459 if ~exist( 'skip3D', 'var' )
2460     skip3D = false;
2461 end
2462 
2463 if ~exist( 'ID_ind', 'var' )
2464     def = intGetDef( clist );
2465     ID_ind = find(cellfun(@(IDX) ~isempty(IDX), strfind(def, 'ID')));
2466 end
2467 
2468 
2469 if isstruct( clist )
2470     clistM = clist;
2471 else
2472     nc = numel( clist );
2473     
2474     data = [];
2475     clistM = [];
2476     
2477     
2478     for ii = 1:nc
2479         if iscell( clist{ii} )
2480             clist_ = intDoMerge( clist{ii}, [], skip3D );
2481         else
2482             clist_ = clist{ii};
2483         end
2484         
2485         if isempty( clistM )
2486             clistM = clist_;
2487         else
2488             % regular clist
2489             maxID = max( clistM.data(:,1) );
2490             
2491             tmp = clist_.data(:,ID_ind);
2492             tmp = tmp + maxID;
2493             tmp(tmp==maxID) = 0;
2494             
2495             clist_.data(:,ID_ind) = tmp;
2496             
2497             ss1 = size( clistM.data );
2498             ss2 = size( clist_.data );
2499             
2500             if ss1(2) ~= ss2(2)
2501                 error( 'Clists with a different number of data descriptors are being compared. Descriptor number must match.' );   
2502             end
2503             
2504             clistM.data = [clistM.data;...
2505                 clist_.data];
2506             
2507             %clist 3D
2508             
2509             if isfield( clist_, 'data3D' ) && ~skip3D
2510                 clist_.data3D(:,1,:) = clist_.data3D(:,1,:) +maxID;
2511                 
2512                 ss1 = size(clistM.data3D);
2513                 ss2 = size(clist_.data3D);
2514                 
2515                 if ss1(2) ~= ss2(2)
2516                    error( 'Clists with a different number of data3D descriptors are being compared. Descriptor number must match.' );   
2517                 end
2518                 
2519                 if numel(ss1) == 2
2520                     ss1(3) = 1;
2521                 end
2522                 
2523                 if numel(ss2) == 2
2524                     ss2(3) = 1;
2525                 end
2526                     
2527                 if ss1(3) >  ss2(3)
2528                     clist_.data3D = cat(3,clist_.data3D,nan( [ss2(1:2),ss1(3)-ss2(3)] ) );
2529                 elseif ss1(3) <  ss2(3)
2530                     clistM.data3D = cat(3,clistM.data3D,nan( [ss1(1:2),ss2(3)-ss1(3)] ) );
2531                 end
2532                 
2533                 clistM.data3D = [clistM.data3D;...
2534                     clist_.data3D];
2535             end
2536         end
2537     end
2538     
2539 end
2540 end
2541 
2542 
2543 %% Merge structure with different fields
2544 function g12 = intMergeStruct( g1, g2)
2545 
2546 ng1 = numel(g1);
2547 ng2 = numel(g2);
2548 
2549 tmp1 = fieldnames( g1 );
2550 tmp2 = fieldnames( g2 );
2551 
2552 names = unique({tmp1{:},tmp2{:}});
2553 nnames = numel(names);
2554 
2555 for ii = (ng1+ng2):-1:1
2556 
2557     tmp_gate = [];
2558     
2559     for jj = 1:nnames
2560         
2561         if ii <= ng1
2562             tmps = g1(ii);
2563         else
2564             tmps = g2(ii-ng1);
2565         end
2566         
2567         if isfield( tmps, names{jj} )
2568             tmp = getfield( tmps, names{jj} );
2569         else
2570            tmp = []; 
2571         end
2572         
2573         tmp_gate = setfield( tmp_gate,  names{jj}, tmp );
2574     end
2575     
2576     g12(ii) = tmp_gate;
2577     
2578 end
2579 end
2580 
2581 %% Load clist from file
2582 function clist = intLoadClist( dirname, data )
2583 
2584 drill_flag = data.drill_flag;
2585 
2586 clist = {};
2587 
2588 
2589 if exist( dirname, 'file' ) == 2
2590     
2591     
2592     [dir_,file_,ext_] = fileparts( dirname );
2593     
2594     if strcmp( ext_, '.mat' )
2595         tmp = load( dirname );
2596         
2597         
2598         if isstruct( tmp ) && isfield( tmp, 'clist' );
2599             clist = tmp.clist;
2600         else
2601             clist = tmp;
2602         end
2603     elseif strcmp( ext_, '.csv' )
2604         clist = intLoadCSV( dirname );
2605     else
2606         error( 'Loading files must be either .mat or .csv' );
2607     end
2608     
2609 else
2610     dirname = fixDir( dirname );
2611 
2612     if ~exist( dirname, 'dir' )
2613         error( ['Directory ', dirname, 'does not exist.' ] );
2614     else
2615         if drill_flag
2616             clist = intRecLoad( {}, dirname, 0 );
2617         else
2618             contentsD = dir(  [dirname, 'xy*'] );
2619             
2620             nc = numel( contentsD );
2621             
2622             if nc == 0
2623                                
2624                 filename = [dirname,'clist.mat'];
2625                 if exist( filename, 'file' );
2626                     clist = load( filename );
2627                     clist.filename = GetFullPath(filename);
2628                 else
2629                     error([ 'Can''t find file ', filename] );
2630                 end
2631                 
2632             else
2633                 
2634                 filename =  [dirname,'header.mat'];               
2635                 if exist(filename ) == 2
2636                     header = load( filename );
2637                 else
2638                     header = [];
2639                 end
2640 
2641                 counter = 0;
2642                 for ii = 1:nc
2643                     dirname_xy = fixDir( [dirname,contentsD(ii).name] );
2644                     
2645                     filename = [dirname_xy,'clist.mat' ];
2646                     
2647                     if exist( filename, 'file' )
2648                         counter = counter+1;
2649                         tmp = load( filename );
2650                         
2651                         tmp.filename = GetFullPath(filename);
2652                           
2653                         clist{counter} = tmp;
2654                         
2655                         if ~isempty(header)
2656                            clist{counter}.name =  header.xydata(ii).geneName;
2657                         end
2658                     end
2659                 end
2660             end
2661         end
2662     end
2663 end
2664 end
2665 
2666 % recursive loading of clist from directory.
2667 function [clist,count] = intRecLoad( clist, dirname, count )
2668 
2669 dirname = fixDir( dirname );
2670 
2671 contents = dir( dirname );
2672 
2673 nc = numel( contents );
2674 
2675 for ii = 1:nc
2676     
2677     if contents( ii).isdir && contents(ii).name(1) ~= '.'
2678         dirname_ii = [dirname,contents(ii).name];
2679         %disp( ['Checking directory ',dirname_ii] );
2680         [clist,count] = intRecLoad( clist, dirname_ii, count );
2681     elseif strcmp( contents(ii).name, 'clist.mat' )
2682         count = count+1;
2683         name = [dirname,'clist.mat'];
2684         disp( ['Loading ',name] );
2685         tmp = load( name );
2686         
2687         if isstruct( tmp ) && isfield( tmp, 'clist' );
2688             clist{1,count} = tmp.clist;
2689         else
2690             clist{1,count} = tmp;
2691         end
2692         
2693         end
2694 end
2695 
2696 
2697 end
2698 
2699 %% squeeze all clists into a single column
2700 function clistS = intSqueeze( varargin )
2701 
2702 if nargin == 1
2703     clistS = {};    
2704     clistS = intSqueeze( clistS, varargin{1} );
2705 elseif nargin == 2
2706     clistS = varargin{1};
2707     clist  = varargin{2};
2708     
2709     nc  = numel( clist );
2710     
2711     for ii = 1:nc
2712        
2713         if iscell( clist{ii} )
2714             clistS = intSqueeze( clistS, clist{ii} );
2715         elseif isstruct( clist{ii} )
2716             clistS = { clistS{:}, clist{ii} }';
2717         else
2718             error( 'Not a clist' );
2719         end
2720     end
2721 end
2722 end
2723 
2724 %% expand all clists into a row.
2725 function clistS = intExpand( varargin )
2726 
2727 if nargin == 1
2728     clistS = {};    
2729     clistS = intExpand( clistS, varargin{1} );
2730 elseif nargin == 2
2731     clistS = varargin{1};
2732     clist  = varargin{2};
2733     
2734     nc  = numel( clist );
2735     
2736     for ii = 1:nc
2737        
2738         if iscell( clist{ii} )
2739             clistS = intExpand( clistS, clist{ii} );
2740         elseif isstruct( clist{ii} )
2741             clistS = { clistS{:}, clist{ii} };
2742         else
2743             error( 'Not a clist' );
2744         end
2745     end
2746 end
2747 end
2748 
2749 %% Get data to return at the command line
2750 function output = intGet( clist, g_ind )
2751 
2752 output = [];
2753 if iscell( clist )
2754     nc = numel(clist);
2755     
2756     for ii = 1:nc
2757         output = [output;  intGet( clist{ii}, g_ind )];
2758     end
2759 else
2760     output = clist.data(:,g_ind);
2761 end
2762 
2763 end
2764 
2765 %% get 3D data out of the structure to return at the command line
2766 function output = intGet3D( clist, g3D_ind )
2767 
2768 output = [];
2769 if iscell( clist )
2770     nc = numel(clist);
2771     
2772     for ii = 1:nc
2773         output = cat(1, output, intGet3D( clist{ii}, g3D_ind ));
2774     end
2775 else
2776     output = clist.data3D(:,g3D_ind,:);
2777 end
2778 
2779 end
2780 
2781 %% Get data out of the structures
2782 function x = intGetData( clist, data, ind, units )
2783 
2784 if ~exist( 'units', 'var' )
2785     units = 1;
2786 end
2787 
2788 if data.time_flag
2789     x = clist.data3D(:,ind,:);
2790     x = x(:);
2791     
2792     x = intApplyGate3D( x, clist );
2793 else
2794     x = clist.data(:,ind);
2795 end
2796 
2797 x = units*x;
2798 
2799 end
2800 
2801 %% Get data out of the structures
2802 function [x,x0,flagger,n] = intGetDataC( clist, data, wind )
2803 
2804 tmp = intGetData( clist, data, data.ind(wind(1)), data.units(wind(1)) );
2805 
2806 n_ind = numel( wind );
2807 
2808 x  = nan( [numel(tmp),n_ind] );
2809 x0 = nan( [numel(tmp),n_ind] );
2810 
2811 for ii = 1:n_ind
2812     tmp = intGetData( clist, data, data.ind(wind(ii)), data.units(wind(ii)) );
2813     
2814     x0(:,ii) = tmp;
2815 
2816     if data.log_flag(wind(ii))
2817         tmp = log(tmp);
2818     end
2819     
2820     x(:,ii) = tmp;
2821 end
2822 
2823 [~,flagger] = fixVals( sum(x,2) );
2824 
2825 x  = x(flagger,:);
2826 x0 = x0(flagger,:);
2827 
2828 n= sum(flagger);
2829 end
2830 
2831 
2832 %% Gate the 3D data
2833 function x = intApplyGate3D( x, clist )
2834 
2835 ss     = size(clist.data3D);
2836 inflag = true(ss(1)*ss(3),1);
2837 
2838 if isfield( clist, 'gate3D' ) && ~isempty ('gate3D.clist')
2839     for ii = 1:numel(clist.gate3D)
2840         if numel(clist.gate3D(ii).ind) == 2
2841             
2842             tmp1 = clist.data3D(:,clist.gate3D(ii).ind(1),:);
2843             tmp2 = clist.data3D(:,clist.gate3D(ii).ind(2),:);
2844             
2845             inflag = and(inflag, inpolygon( tmp1(:), tmp2(:), ...
2846                 clist.gate3D(ii).xx(:,1), clist.gate3D(ii).xx(:,2) ));
2847         else
2848             tmp = clist.data3D(:,clist.gate3D(ii).ind,:);
2849             inflag = and( inflag, and( tmp(:) > min(clist.gate3D(ii).x), tmp(:) < max(clist.gate3D(ii).x)));
2850         end
2851     end
2852 end
2853 
2854 x = x(inflag);
2855 
2856 end
2857 
2858 %% Add time fields to 3D data structure
2859 function clist = intDoAddT( clist )
2860 
2861 if iscell( clist )
2862     nc = numel(clist);
2863     
2864     for ii = 1:nc
2865         clist{ii} = intDoAddT( clist{ii} );
2866     end
2867 elseif isstruct( clist )
2868     ss = size( clist.data3D );
2869     
2870     [~,tmp] = gateTool( clist, 'get', 2, 'time' );
2871     
2872     if numel(ss) == 2
2873         ss(3) = 1;
2874     end
2875     len  = reshape( ~isnan(squeeze(tmp)),[ss(1),ss(3)]);
2876     age = cumsum( len, 2 );
2877     age(~len) = nan;
2878     
2879     age_rel = age;
2880     age_rel = age./(max(age,[],2)*ones([1,size(age,2)]));
2881     
2882     time = ones([ss(1),1])*(1:ss(3)); 
2883     
2884     clist = gateTool( clist, 'add3D', time, 'Time (Frames)' );
2885     clist = gateTool( clist, 'add3D', age, 'Age (Frames)' );
2886     clist = gateTool( clist, 'add3D', age_rel, 'Relative Age' );
2887 else
2888     error( 'Internal error. not clist' );
2889 end
2890 
2891 end
2892 
2893 %% Clear gates
2894 function clist = intClear( clist, ind )
2895 
2896 if iscell( clist )
2897     nc = numel(clist);
2898     
2899     for ii = 1:nc
2900         clist{ii} = intClear( clist{ii}, ind );
2901     end
2902 elseif isstruct( clist )
2903     clist = gateStrip( clist, ind );
2904 end
2905 
2906 end
2907 
2908 %% output csv and xls files
2909 function intcsv( clist, data );
2910 
2911 
2912 filename = data.export_filename;
2913 
2914 disp( 'Warning: All lists contained in clist will be stripped (ungated data removed) and merged (multiple lists combined) before xls export.');
2915 
2916 
2917 if ~data.time_flag
2918     clist = gateTool( clist, 'strip', 'skip3D' );
2919     clist = gateTool( clist, 'merge', 'skip3D' );
2920     
2921     tmp1 = num2cell( clist.data );
2922     tmp2 = reshape( clist.def, [1,numel(clist.def)] );
2923     
2924     tmp = cat(1,tmp2,tmp1);
2925 else
2926     clist = gateTool( clist, 'strip');
2927     clist = gateTool( clist, 'merge');
2928     
2929     if isfield( clist, 'data3D' )
2930         if ~isfield( data, 'export_index' ) || isempty( clist.data3D ) || isempty( data.export_index )
2931             error( 'Need an export index to export data3D' );
2932         elseif  ~(0<data.export_index) && data.export_index<=size(clist.data3D,2)
2933             error( 'Index outside the range of allowed indices for data3D' );
2934         else
2935             tmp = squeeze( clist.data3D(:,data.export_index,:) );
2936         end
2937     else
2938         error( 'No data3D field.' );
2939     end
2940 end
2941 
2942 if data.which_export_flag == 1
2943     csvwrite2( filename, tmp );
2944 else
2945     disp( 'Warning: This function only works if excel is installed. Complain to matlab (ie mathworks) not me.' );
2946     
2947     xlswrite( filename, tmp );
2948 end
2949 
2950 end
2951 
2952 %% crappy csv output written due to problems with matlabs implementation
2953 function csvwrite2( filename, data )
2954 
2955 
2956 cellflag = iscell( data );
2957 
2958 nn = size( data );
2959 
2960 fid = fopen(filename, 'w') ;
2961 
2962 if fid
2963     for ii = 1:nn(1)
2964         for jj = 1:nn(2)
2965             
2966             if cellflag
2967                 tmp = data{ii,jj};
2968             else
2969                 tmp = data(ii,jj);
2970             end
2971             
2972             if ischar( tmp )
2973                 fprintf(fid, '%s', tmp);
2974             elseif isnumeric( tmp )
2975                 if numel( tmp ) == 1
2976                     fprintf(fid, '%e', tmp);
2977                 else
2978                     error( 'No nonscalar allowed in csv.' );
2979                 end
2980             else
2981                 error( 'un recognized type in csv.' );
2982             end
2983             
2984             if jj ~= nn(2);
2985                 fprintf(fid, '%c', ',' );
2986             end
2987         end
2988         fprintf(fid, '\n');
2989     end
2990     fclose(fid) ;
2991 end
2992 end
2993 
2994 
2995 %% Get 3D field definition from the structure
2996 function clist = intFixDef3D( clist );
2997 
2998 
2999 if isstruct( clist )
3000     % convert struct data to clist
3001     if ~isfield( clist, 'data' ) || ~isfield( clist, 'def' )
3002         disp( 'Trying to convert structure to clist.' )
3003         
3004         fieldnames_  = fieldnames( clist )';
3005         tmp  =  { 'Cell ID',fieldnames_{:}};
3006         
3007         ntmp = numel( tmp );
3008         
3009         %for ii = 1:ntmp
3010             %tmp{ii} = [num2str(ii),' : ',tmp{ii}];
3011         %
3012         %end
3013         
3014         def = tmp;
3015         clist_conv.def = def;
3016         
3017         nc =  numel( clist );
3018         
3019         if nc == 1
3020             ncc = numel( getfield( clist, fieldnames_{1} ) );
3021         else
3022             ncc = nc;
3023         end
3024         
3025         clist_conv.data = nan( [ncc,ntmp] );
3026         clist_conv.data(:,1) = 1:ncc;
3027         
3028         for ii = 2:ntmp
3029             if nc ~= 1
3030                 tmp_ = drill( clist, fieldnames_{ii-1} );
3031             else
3032                 tmp_ = getfield( clist, fieldnames_{ii-1} );
3033             end
3034             
3035             if isnumeric( tmp_ )
3036                 clist_conv.data(:,ii) = tmp_;
3037             end
3038             
3039         end
3040         
3041         clist = clist_conv;
3042     end
3043     
3044     if isfield( clist, 'def3d' )
3045         clist.def3D = clist.def3d;
3046         clist = rmfield( clist, 'def3d' );
3047     end
3048     
3049     % strip out header numbers if they exist
3050     if ~isempty( clist )
3051         if isfield( clist, 'def' )
3052             clist.def = intRemoveNumDef( clist.def );
3053         end
3054         if isfield( clist, 'def3D' )
3055             clist.def3D = intRemoveNumDef( clist.def3D );
3056         end
3057     end
3058     
3059 elseif iscell( clist )
3060     nc = numel( clist );
3061     for ii = 1:nc
3062         clist{ii} = intFixDef3D( clist{ii} );
3063     end
3064 end
3065 
3066 
3067 
3068 end
3069 
3070 % legacy issues. Strip out numbers from clists defs
3071 function def = intRemoveNumDef( def )
3072 nd = numel( def );
3073 
3074 tmp = def{1};
3075 tmp = tmp(tmp~=' ' );
3076 if numel( tmp ) > 1 && strcmp( tmp(1:2), '1:' )
3077     for ii = 1:nd
3078         ind = find( def{ii} == ':', 1, 'last' );
3079         if ~isempty(ind)
3080            if all(ismember(def{ii}(1:ind),'0123456789 :' ))
3081                def{ii} = def{ii}(ind+1:end);
3082                ind = find( def{ii}~=' ',1, 'first');
3083                if ~isempty( ind )
3084                    def{ii} = def{ii}(ind:end);
3085                end
3086            end
3087         end
3088     end
3089 end
3090 end
3091 
3092 
3093 function intSaveClist( data )
3094 
3095 clist = data.clist;
3096 
3097 if isstruct( clist )
3098     save( data.save_name, '-struct', 'clist' );
3099 else
3100     save( data.save_name, 'clist' ); 
3101 end
3102 
3103 end
3104 
3105 % Draw Kolmogorov-Smirnov p value
3106 function intShowKS( data )
3107 if isfield( data, 'stat' )
3108 
3109 ns = numel( data.stat );
3110 
3111 pp = nan( [ns,ns] );
3112 dd = nan( [ns,ns] );
3113 for ii = 1:ns
3114     for jj = 1:ii
3115         [dd_,pp_] = kstest2( data.stat(ii).x, data.stat(jj).x );
3116         
3117         pp(ii,jj) = pp_;
3118         pp(jj,ii) = pp_;
3119         
3120         dd(ii,jj) = dd_;
3121         dd(jj,ii) = dd_;     
3122     end
3123 end
3124 
3125 figure;
3126 subplot( 1,2,1);
3127 imagesc( pp );
3128 colormap default;
3129 set( gca, 'Ytick', 1:ns )
3130 set( gca, 'Yticklabels', {data.stat.name0} )
3131 set( gca, 'Xtick', 1:ns )
3132 set( gca, 'Xticklabels', {data.stat.name0} )
3133 set( gca, 'XTickLabelRotation', 90 )
3134 axis equal tight
3135 title( 'K-S P value' );
3136 colorbar
3137 caxis([0,1]);
3138 
3139 subplot( 1,2,2);
3140 imagesc( dd );
3141 colormap default;
3142 set( gca, 'Ytick', 1:ns )
3143 set( gca, 'Yticklabels', {data.stat.name0} )
3144 set( gca, 'Xtick', 1:ns )
3145 set( gca, 'Xticklabels', {data.stat.name0} )
3146 set( gca, 'XTickLabelRotation', 90 )
3147 axis equal tight
3148 title( 'Statistically Distinct' );
3149 colorbar
3150 caxis([0,1]);
3151 
3152 
3153 end
3154 end
3155 
3156 
3157 
3158 function clist = intLoadCSV( name )
3159 
3160 fileptr = fopen( name );
3161 
3162 if ~fileptr
3163     error( ['Can''t load file: ',name] );
3164 end
3165 
3166 str = fgets( fileptr );
3167 
3168 def = textscan(str,'%s','Delimiter',',');
3169 def = def{1}';
3170 
3171 nd = numel( def );
3172 
3173 for ii = 1:nd
3174     def{ii} = [num2str(ii),' : ',def{ii}];
3175 end
3176 
3177 clist.def = def;
3178 
3179 wflag = true;
3180 
3181 data = [];
3182 
3183 while wflag
3184     
3185     str = fgets( fileptr );
3186     
3187     if isnumeric( str ) && str == -1
3188         wflag = false;
3189     else
3190         
3191         ent = textscan(str,'%s','Delimiter',',');
3192         ent = ent{1};
3193         ent = cellfun( @str2num,ent )';
3194         
3195         data = [data;ent];
3196     end
3197     
3198 end
3199 
3200 clist.data = data;
3201 
3202 fclose( fileptr );
3203 
3204 end
3205 
3206 %% This stuff is from  Jan Simon on the matlab file exchange
3207 function File = GetFullPath(File, Style)
3208 % GetFullPath - Get absolute canonical path of a file or folder
3209 % Absolute path names are safer than relative paths, when e.g. a GUI or TIMER
3210 % callback changes the current directory. Only canonical paths without "." and
3211 % ".." can be recognized uniquely.
3212 % Long path names (>259 characters) require a magic initial key "\\?\" to be
3213 % handled by Windows API functions, e.g. for Matlab's FOPEN, DIR and EXIST.
3214 %
3215 % FullName = GetFullPath(Name, Style)
3216 % INPUT:
3217 %   Name:  String or cell string, absolute or relative name of a file or
3218 %          folder. The path need not exist. Unicode strings, UNC paths and long
3219 %          names are supported.
3220 %   Style: Style of the output as string, optional, default: 'auto'.
3221 %          'auto': Add '\\?\' or '\\?\UNC\' for long names on demand.
3222 %          'lean': Magic string is not added.
3223 %          'fat':  Magic string is added for short names also.
3224 %          The Style is ignored when not running under Windows.
3225 %
3226 % OUTPUT:
3227 %   FullName: Absolute canonical path name as string or cell string.
3228 %          For empty strings the current directory is replied.
3229 %          '\\?\' or '\\?\UNC' is added on demand.
3230 %
3231 % NOTE: The M- and the MEX-version create the same results, the faster MEX
3232 %   function works under Windows only.
3233 %   Some functions of the Windows-API still do not support long file names.
3234 %   E.g. the Recycler and the Windows Explorer fail even with the magic '\\?\'
3235 %   prefix. Some functions of Matlab accept 260 characters (value of MAX_PATH),
3236 %   some at 259 already. Don't blame me.
3237 %   The 'fat' style is useful e.g. when Matlab's DIR command is called for a
3238 %   folder with les than 260 characters, but together with the file name this
3239 %   limit is exceeded. Then "dir(GetFullPath([folder, '\*.*], 'fat'))" helps.
3240 %
3241 % EXAMPLES:
3242 %   cd(tempdir);                    % Assumed as 'C:\Temp' here
3243 %   GetFullPath('File.Ext')         % 'C:\Temp\File.Ext'
3244 %   GetFullPath('..\File.Ext')      % 'C:\File.Ext'
3245 %   GetFullPath('..\..\File.Ext')   % 'C:\File.Ext'
3246 %   GetFullPath('.\File.Ext')       % 'C:\Temp\File.Ext'
3247 %   GetFullPath('*.txt')            % 'C:\Temp\*.txt'
3248 %   GetFullPath('..')               % 'C:\'
3249 %   GetFullPath('..\..\..')         % 'C:\'
3250 %   GetFullPath('Folder\')          % 'C:\Temp\Folder\'
3251 %   GetFullPath('D:\A\..\B')        % 'D:\B'
3252 %   GetFullPath('\\Server\Folder\Sub\..\File.ext')
3253 %                                   % '\\Server\Folder\File.ext'
3254 %   GetFullPath({'..', 'new'})      % {'C:\', 'C:\Temp\new'}
3255 %   GetFullPath('.', 'fat')         % '\\?\C:\Temp\File.Ext'
3256 %
3257 % COMPILE:
3258 %   Automatic: InstallMex GetFullPath.c uTest_GetFullPath
3259 %   Manual:    mex -O GetFullPath.c
3260 %   Download:  http://www.n-simon.de/mex
3261 % Run the unit-test uTest_GetFullPath after compiling.
3262 %
3263 % Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
3264 %         Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008/2010
3265 % Assumed Compatibility: higher Matlab versions
3266 % Author: Jan Simon, Heidelberg, (C) 2009-2013 matlab.THISYEAR(a)nMINUSsimon.de
3267 %
3268 % See also: CD, FULLFILE, FILEPARTS.
3269 
3270 % $JRev: R-G V:032 Sum:7Xd/JS0+yfax Date:15-Jan-2013 01:06:12 $
3271 % $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
3272 % $UnitTest: uTest_GetFullPath $
3273 % $File: Tools\GLFile\GetFullPath.m $
3274 % History:
3275 % 001: 20-Apr-2010 22:28, Successor of Rel2AbsPath.
3276 % 010: 27-Jul-2008 21:59, Consider leading separator in M-version also.
3277 % 011: 24-Jan-2011 12:11, Cell strings, '~File' under linux.
3278 %      Check of input types in the M-version.
3279 % 015: 31-Mar-2011 10:48, BUGFIX: Accept [] as input as in the Mex version.
3280 %      Thanks to Jiro Doke, who found this bug by running the test function for
3281 %      the M-version.
3282 % 020: 18-Oct-2011 00:57, BUGFIX: Linux version created bad results.
3283 %      Thanks to Daniel.
3284 % 024: 10-Dec-2011 14:00, Care for long names under Windows in M-version.
3285 %      Improved the unittest function for Linux. Thanks to Paul Sexton.
3286 % 025: 09-Aug-2012 14:00, In MEX: Paths starting with "\\" can be non-UNC.
3287 %      The former version treated "\\?\C:\<longpath>\file" as UNC path and
3288 %      replied "\\?\UNC\?\C:\<longpath>\file".
3289 % 032: 12-Jan-2013 21:16, 'auto', 'lean' and 'fat' style.
3290 
3291 % Initialize: ==================================================================
3292 % Do the work: =================================================================
3293 
3294 % #############################################
3295 % ### USE THE MUCH FASTER MEX ON WINDOWS!!! ###
3296 % #############################################
3297 
3298 % Difference between M- and Mex-version:
3299 % - Mex does not work under MacOS/Unix.
3300 % - Mex calls Windows API function GetFullPath.
3301 % - Mex is much faster.
3302 
3303 % Magix prefix for long Windows names:
3304 if nargin < 2
3305    Style = 'auto';
3306 end
3307 
3308 % Handle cell strings:
3309 % NOTE: It is faster to create a function @cell\GetFullPath.m under Linux, but
3310 % under Windows this would shadow the fast C-Mex.
3311 if isa(File, 'cell')
3312    for iC = 1:numel(File)
3313       File{iC} = GetFullPath(File{iC}, Style);
3314    end
3315    return;
3316 end
3317 
3318 % Check this once only:
3319 isWIN    = strncmpi(computer, 'PC', 2);
3320 MAX_PATH = 260;
3321 
3322 % Warn once per session (disable this under Linux/MacOS):
3323 persistent hasDataRead
3324 if isempty(hasDataRead)
3325    % Test this once only - there is no relation to the existence of DATAREAD!
3326    %if isWIN
3327    %   Show a warning, if the slower Matlab version is used - commented, because
3328    %   this is not a problem and it might be even useful when the MEX-folder is
3329    %   not inlcuded in the path yet.
3330    %   warning('JSimon:GetFullPath:NoMex', ...
3331    %      ['GetFullPath: Using slow Matlab-version instead of fast Mex.', ...
3332    %       char(10), 'Compile: InstallMex GetFullPath.c']);
3333    %end
3334    
3335    % DATAREAD is deprecated in 2011b, but still available. In Matlab 6.5, REGEXP
3336    % does not know the 'split' command, therefore DATAREAD is preferred:
3337    hasDataRead = ~isempty(which('dataread'));
3338 end
3339 
3340 if isempty(File)  % Accept empty matrix as input:
3341    if ischar(File) || isnumeric(File)
3342       File = cd;
3343       return;
3344    else
3345       error(['JSimon:', mfilename, ':BadTypeInput1'], ...
3346          ['*** ', mfilename, ': Input must be a string or cell string']);
3347    end
3348 end
3349 
3350 if ischar(File) == 0  % Non-empty inputs must be strings
3351    error(['JSimon:', mfilename, ':BadTypeInput1'], ...
3352       ['*** ', mfilename, ': Input must be a string or cell string']);
3353 end
3354 
3355 if isWIN  % Windows: --------------------------------------------------------
3356    FSep = '\';
3357    File = strrep(File, '/', FSep);
3358    
3359    % Remove the magic key on demand, it is appended finally again:
3360    if strncmp(File, '\\?\', 4)
3361       if strncmpi(File, '\\?\UNC\', 8)
3362          File = ['\', File(7:length(File))];  % Two leading backslashes!
3363       else
3364          File = File(5:length(File));
3365       end
3366    end
3367    
3368    isUNC   = strncmp(File, '\\', 2);
3369    FileLen = length(File);
3370    if isUNC == 0                        % File is not a UNC path
3371       % Leading file separator means relative to current drive or base folder:
3372       ThePath = cd;
3373       if File(1) == FSep
3374          if strncmp(ThePath, '\\', 2)   % Current directory is a UNC path
3375             sepInd  = strfind(ThePath, '\');
3376             ThePath = ThePath(1:sepInd(4));
3377          else
3378             ThePath = ThePath(1:3);     % Drive letter only
3379          end
3380       end
3381       
3382       if FileLen < 2 || File(2) ~= ':'  % Does not start with drive letter
3383          if ThePath(length(ThePath)) ~= FSep
3384             if File(1) ~= FSep
3385                File = [ThePath, FSep, File];
3386             else                        % File starts with separator:
3387                File = [ThePath, File];
3388             end
3389          else                           % Current path ends with separator:
3390             if File(1) ~= FSep
3391                File = [ThePath, File];
3392             else                        % File starts with separator:
3393                ThePath(length(ThePath)) = [];
3394                File = [ThePath, File];
3395             end
3396          end
3397          
3398       elseif FileLen == 2 && File(2) == ':'   % "C:" current directory on C!
3399          % "C:" is the current directory on the C-disk, even if the current
3400          % directory is on another disk! This was ignored in Matlab 6.5, but
3401          % modern versions considers this strange behaviour.
3402          if strncmpi(ThePath, File, 2)
3403             File = ThePath;
3404          else
3405             try
3406                File = cd(cd(File));
3407             catch    % No MException to support Matlab6.5...
3408                if exist(File, 'dir')  % No idea what could cause an error then!
3409                   rethrow(lasterror);
3410                else  % Reply "K:\" for not existing disk:
3411                   File = [File, FSep];
3412                end
3413             end
3414          end
3415       end
3416    end
3417    
3418 else         % Linux, MacOS: ---------------------------------------------------
3419    FSep = '/';
3420    File = strrep(File, '\', FSep);
3421    
3422    if strcmp(File, '~') || strncmp(File, '~/', 2)  % Home directory:
3423       HomeDir = getenv('HOME');
3424       if ~isempty(HomeDir)
3425          File(1) = [];
3426          File    = [HomeDir, File];
3427       end
3428       
3429    elseif strncmpi(File, FSep, 1) == 0
3430       % Append relative path to current folder:
3431       ThePath = cd;
3432       if ThePath(length(ThePath)) == FSep
3433          File = [ThePath, File];
3434       else
3435          File = [ThePath, FSep, File];
3436       end
3437    end
3438 end
3439 
3440 % Care for "\." and "\.." - no efficient algorithm, but the fast Mex is
3441 % recommended at all!
3442 if ~isempty(strfind(File, [FSep, '.']))
3443    if isWIN
3444       if strncmp(File, '\\', 2)  % UNC path
3445          index = strfind(File, '\');
3446          if length(index) < 4    % UNC path without separator after the folder:
3447             return;
3448          end
3449          Drive            = File(1:index(4));
3450          File(1:index(4)) = [];
3451       else
3452          Drive     = File(1:3);
3453          File(1:3) = [];
3454       end
3455    else  % Unix, MacOS:
3456       isUNC   = false;
3457       Drive   = FSep;
3458       File(1) = [];
3459    end
3460    
3461    hasTrailFSep = (File(length(File)) == FSep);
3462    if hasTrailFSep
3463       File(length(File)) = [];
3464    end
3465    
3466    if hasDataRead
3467       if isWIN  % Need "\\" as separator:
3468          C = dataread('string', File, '%s', 'delimiter', '\\');  %#ok<REMFF1>
3469       else
3470          C = dataread('string', File, '%s', 'delimiter', FSep);  %#ok<REMFF1>
3471       end
3472    else  % Use the slower REGEXP, when DATAREAD is not available anymore:
3473       C = regexp(File, FSep, 'split');
3474    end
3475    
3476    % Remove '\.\' directly without side effects:
3477    C(strcmp(C, '.')) = [];
3478    
3479    % Remove '\..' with the parent recursively:
3480    R = 1:length(C);
3481    for dd = reshape(find(strcmp(C, '..')), 1, [])
3482       index    = find(R == dd);
3483       R(index) = [];
3484       if index > 1
3485          R(index - 1) = [];
3486       end
3487    end
3488    
3489    if isempty(R)
3490       File = Drive;
3491       if isUNC && ~hasTrailFSep
3492          File(length(File)) = [];
3493       end
3494       
3495    elseif isWIN
3496       % If you have CStr2String, use the faster:
3497       %   File = CStr2String(C(R), FSep, hasTrailFSep);
3498       File = sprintf('%s\\', C{R});
3499       if hasTrailFSep
3500          File = [Drive, File];
3501       else
3502          File = [Drive, File(1:length(File) - 1)];
3503       end
3504       
3505    else  % Unix:
3506       File = [Drive, sprintf('%s/', C{R})];
3507       if ~hasTrailFSep
3508          File(length(File)) = [];
3509       end
3510    end
3511 end
3512 
3513 % "Very" long names under Windows:
3514 if isWIN
3515    if ~ischar(Style)
3516       error(['JSimon:', mfilename, ':BadTypeInput2'], ...
3517          ['*** ', mfilename, ': Input must be a string or cell string']);
3518    end
3519    
3520    if (strncmpi(Style, 'a', 1) && length(File) >= MAX_PATH) || ...
3521          strncmpi(Style, 'f', 1)
3522       % Do not use [isUNC] here, because this concerns the input, which can
3523       % '.\File', while the current directory is an UNC path.
3524       if strncmp(File, '\\', 2)  % UNC path
3525          File = ['\\?\UNC', File(2:end)];
3526       else
3527          File = ['\\?\', File];
3528       end
3529    end
3530 end
3531 end
3532 % return;

Generated on Thu 19-Jan-2017 13:55:21 by m2html © 2005