itaHRTF.m 76.1 KB
Newer Older
1 2
classdef  itaHRTF < itaAudio
    
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    %ITAHRTF - class to deal with HRTFs
    %
    %   Examples:
    %   hrtf = itaHRTF('sofa','TU-Berlin_QU_KEMAR_anechoic_radius_1m.sofa')
    %
    % These objects can be used like itaAudios and helps to find HRTF angles
    % quickly. In addition different methods are implemented to evaluate
    % binaural parameters and interpolate the data set.
    %
    % itaHRTF Properties:
    %         dirCoord          Measured directions
    %         EarSide           Ear side ('L' left or 'R' right) of each channel
    %         TF_type           [HRTF DTF Recording]
    %         sphereType        [ring cap sphere undefined]
    %
    %         resAzimuth        resolution in azimuth (only equiangular)
    %         resElevation      resolution in elevation (only equiangular)
    %
    %         rangeAzimuth      min. and max. angle in azimuth
    %         rangeElevation 	min. and max. angle in elevation
    %
    %         nPointsAzimuth    number of directions in azimuth
    %         nPointsElevation  number of directions in elevation
    %
    %         nPoints           total number of directions
    %
    %         mMetadata         stored metadata from a loaded daff file
    %
    % itaHRTF Methods (find & select directions):
    %         HRTFfind  = findnearestHRTF(varargin)
    %         HRTFdir   = direction(idxCoord)
    %         thetaUni  = theta_Unique
    %         phiUni    = phi_Unique
    %         slice     = sphericalSlice(dirID,dir_deg)
    %         HRTF_left   = getEar(earSide)
    %
    % itaHRTF Methods (play):
    %         play_gui(stimulus)
    %
    % itaHRTF Methods (store):
    %         audioHRTF = itaHRTF2itaAudio
    %                     writeDAFFFile(filePath)
    %
    % itaHRTF Methods (binaural parameter):
    %         ITD       = ITD(varargin)
    %         t0        = meanTimeDelay(varargin)
    %         ILD       = ILD(varargin)
    %
    % itaHRTF Methods (manipulation):
    %         DTF       = calcDTF
    %         HRTF_int  = interp(varargin)
    %
    % itaHRTF Methods (plot):
    %         plot_ITD(varargin)
    %         plot_freqSlice(varargin)
    
    %
    %  See also:
    %   itaAudio, test_rbo_postprocessing_HRTF_arc_CropDiv
    %
    %   Reference page in Help browser
    %        <a href="matlab:doc itaHRTF">doc itaHRTF</a>
    
    % <ITA-Toolbox>
    % This file is part of the application HRTF_class for the ITA-Toolbox. All rights reserved.
    % You can find the license for this m-file in the application folder.
    % </ITA-Toolbox>
    
    
    % Author: Ramona Bomhardt -- Email: rbo@akustik.rwth-aachen.de
    % Created:  10-Jul-2014
rbo's avatar
rbo committed
74

75
    properties (Access = private)
76
        mMetadata   = [];
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        mCoordSave  = [];
        mChNames    = [];
        mDirCoord   = itaCoordinates;
        mEarSide    = [];
        mTF_type    = 'HRTF';
        mSphereType = 'undefined';
    end
    
    properties (Dependent = true, Hidden = false)
        dirCoord = itaCoordinates;
        EarSide  = [];
        TF_type  = 'HRTF';
        sphereType = 'undefined';
        
        resAzimuth      = 5;
        resElevation    = 5;
        
        rangeAzimuth    = [0 359];
        rangeElevation  = [0 180];
        
        nPointsAzimuth  = 72;
        nPointsElevation= 37;
        
        nPoints         = [];
        phi_Offset      = zeros(37,1);
    end
    
    properties (Dependent = true, Hidden = true)
        
    end
    
    properties (Dependent = true, SetAccess = private)
109
        openDAFF2itaHRTF;
110 111 112 113 114 115 116 117 118 119
        itaAudio2itaHRTF;
        init;
        hdf2itaHRTF;
        sofa2itaHRTF;
        nDirections = [];
    end
    
    methods % Special functions that implement operations that are usually performed only on instances of the class
        %% Input
        function this = itaHRTF(varargin)
120
            iniAudio = [];
121
            % initialize itaHRTF with itaAudio properties (only for nargin == 1)
rbo's avatar
rbo committed
122 123
            if nargin > 1 || (nargin == 1 && (ischar(varargin{1}) || isa(varargin{1},'itaAudio')))
                iniAudio = [];
rbo's avatar
rbo committed
124 125 126 127 128
            elseif nargin == 1 && isstruct(varargin{1})
                fNames = {'domain','data','signalType','samplingRate'};
                for idxFN = 1:numel(fNames)
                    iniAudio.(fNames{idxFN}) = varargin{1}.(fNames{idxFN});
                end
129 130 131 132
            end
                            
            this = this@itaAudio(iniAudio);

133
            if nargin >1
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
                % itaAudio input
                TF_types = this.propertiesTF_type;
                for iTF = 1:numel(TF_types)
                    if ~isempty(find(strcmpi(varargin, TF_types{iTF})==1, 1))
                        this.itaAudio2itaHRTF = varargin{find(strcmpi(varargin, TF_types{iTF})==1)-1};
                        this.TF_type = TF_types(iTF);
                    end
                end
                
                % init
                if nargin == 4
                    this.init = varargin;
                end
                % openDaff input
                if ~isempty(find(strcmpi(varargin,'Daff')==1, 1))
150
                    this.openDAFF2itaHRTF = varargin{find(strcmpi(varargin,'Daff')==1)+1};
151 152 153 154 155 156 157 158 159 160 161
                end
                % hdf5 input
                if ~isempty(find(strcmpi(varargin,'hdf5')==1, 1))
                    this.hdf2itaHRTF = varargin{find(strcmpi(varargin,'hdf5')==1)+1};
                end
                % sofa input
                if ~isempty(find(strcmpi(varargin,'SOFA')==1, 1))
                    this.sofa2itaHRTF = varargin{find(strcmpi(varargin,'SOFA')==1)+1};
                end
                
            elseif nargin == 1
162

163 164 165 166 167 168 169 170 171 172 173 174 175
                if isa(varargin{1},'itaHRTF')
                    this = varargin{1};
                    
                elseif nargin ==1 && isstruct(varargin{1}) % only for loading
                    obj = varargin{1};
                    this.data = obj.data;
                    
                    this.signalType = 'energy';
                    % additional itaHRTF data
                    if datenum(2014,7,5)<obj.dateCreated, objFNsaved = this.propertiesSaved;
                    else objFNsaved = this.oldPropertiesSaved;
                    end
                    objFNload = this.propertiesLoad;
176
                    
177 178 179 180 181 182 183 184
                    for i1 = 1:numel(objFNload)
                        this.(objFNload{i1}) = obj.(objFNsaved{i1});
                    end
                    % saving itaCoordinates in itaHRTF does not work at the
                    % moment
                    this.dirCoord.sph = this.mCoordSave;
                    % saving channelNames in itaHRTF does not work at the
                    % moment
185 186
                    this.channelNames = cellstr(this.mChNames);

187 188
                elseif isa(varargin{1},'itaAudio')
                    this.itaAudio2itaHRTF = varargin{1};
rbo's avatar
rbo committed
189 190 191 192 193 194 195
                    
                elseif ischar(varargin{1}) % openDaff/ sofa/ hdf5 input
                    if strfind(lower(varargin{1}),'.daff'), this.openDAFF2itaHRTF = varargin{1};
                    elseif strfind(lower(varargin{1}),'.hdf5'), this.hdf2itaHRTF = varargin{1};
                    elseif strfind(lower(varargin{1}),'.sofa'), this.sofa2itaHRTF = varargin{1};
                    end
                 end
196 197 198 199
            end
        end
        
        %% ......................GET.......................................
200
        
201
        function nDirections = get.nDirections(this)
202
            [~,idxDim] =  uniquetol([this.channelCoordinates.phi_deg this.channelCoordinates.theta_deg] ,'ByRows',true);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
            nDirections = numel(idxDim);
        end
        
        function dirCoord = get.dirCoord(this)
            dirCoord = this.channelCoordinates.n(1:2:this.dimensions);
        end
        
        function EarSide = get.EarSide(this)
            EarSide = this.mEarSide;
            if numel(this.mEarSide)~=this.dimensions
                EarSide = repmat(['L'; 'R'],this.dirCoord.nPoints, 1);
            end
        end
        
        function TF_type = get.TF_type(this)
            TF_type = this.mTF_type; end
        
        function sphereType = get.sphereType(this)
            % aktuell wird noch nicht erkannt, wenn die theta Winkel
            % kontinuierlich ansteigen. Dann gibt es keinen Bruch...
            
            numPhi = numel(this.phi_Unique);
            numTheta = numel(this.theta_Unique);
            
            deltaPhi_deg = 360/numPhi;
            deltaTheta_deg = 180/numTheta;
            
            gradPhi_deg = gradient(rad2deg(this.phi_Unique)) ;
            gradTheta_deg = gradient(rad2deg(this.theta_Unique));
            
            tmpPhi = round(deltaPhi_deg-gradPhi_deg);
            tmpTheta = round(deltaTheta_deg-gradTheta_deg);
            
            if sum(tmpPhi)==0 && sum(tmpTheta)==0 && sum(gradTheta_deg)==180
                sphereType = 'full';
            elseif sum(tmpPhi)==0 && numel(tmpTheta)==1 && tmpTheta(1)==180
                sphereType = 'ring';
            elseif   sum(tmpPhi)==0 && sum(gradTheta_deg)<180
                sphereType = 'cap';
            else
                sphereType = 'undefined';
            end
        end
        
        function resAzi = get.resAzimuth(this)
            resAzi = round(median(diff(rad2deg(this.phi_Unique))));
        end
        
        function resElevation = get.resElevation(this)
            resElevation = round(median(diff(rad2deg(this.theta_Unique))));
        end
        
        function nPointsAzi = get.nPointsAzimuth(this)
            nPointsAzi = numel(this.phi_Unique);
        end
        
        function nPointsEle = get.nPointsElevation(this)
            nPointsEle = numel(this.theta_Unique);
        end
        
        function rangeAzi = get.rangeAzimuth(this)
            rangeAzi = uint16([min(rad2deg(this.phi_Unique)) max(rad2deg(this.phi_Unique))]);
        end
        
        function rangeEle = get.rangeElevation(this)
            rangeEle = uint16([min(rad2deg(this.theta_Unique)) max(rad2deg(this.theta_Unique))]);
        end
        
        function phi_Offset = get.phi_Offset(this)
            thetaU      = this.theta_Unique;
            phi_Offset  = zeros(numel(thetaU),1);
            for idxT = 1:numel(thetaU)
                phi_Offset(idxT,1) = test_rbo_azimuthOffset0(this.sphericalSlice('theta_deg',rad2deg(thetaU(idxT))));
            end
        end
        %% ..............SET PRIVAT........................................
279
        
280
        function this = set.itaAudio2itaHRTF(this,HRTF)
281
            if isa(HRTF,'itaAudio')
282
                % Multi instance?
283
                if numel(HRTF)>1
284 285 286 287 288 289 290 291
                    if numel(HRTF)>1000 % takes a while
                        ita_verbose_info(' A lot of data ...please wait... don''t use itaAudio multi instances for the next time!', 0);
                    end
                    coordinates = HRTF(1).channelCoordinates;
                    if (coordinates.nPoints == 2) & (sum(isnan(coordinates.sph)) < numel(coordinates.sph))
                        ita_verbose_info('Found NaNs in the coordinates. I will copy existing coordinates');
                        
                        for index = 1:length(HRTF)
292 293 294
                            coordinates = HRTF(index).channelCoordinates;
                            coordinates.sph = repmat(coordinates.sph(1,:),2,1);
                            HRTF(index).channelCoordinates = coordinates;
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                        end
                        
                    end
                    HRTFc = HRTF.merge;
                    
                else HRTFc = HRTF;
                end
                
                % coordinates available?
                if isnan(HRTFc.channelCoordinates.cart)
                    error('itaHRTF:Def', ' No channelCoordinates available')
                end
                
                coord = HRTFc.channelCoordinates;
                
                % find the corresponding left and right channel
                pairs  = zeros(coord.nPoints/2,2);
                
                if coord.nPoints>10000 % takes a while
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
314
                    ita_verbose_info([num2str(coord.nPoints) ' Points have to be sorted ...please wait...'], 0);
315 316 317 318
                end
                
                
                counter = 1;
319 320 321 322 323 324
                thetaPhi = round([coord.theta_deg coord.phi_deg]*10)/10; %round to 0.1 deg
                deletedChannel = 0; 
                for iCoord = 1:coord.nPoints
                    coordCurrent = thetaPhi(iCoord,:);
%                     if isempty(find(pairs(:) == iCoord, 1)) % only if the corresponding channel is not found
                    if ~any(pairs(:) == iCoord) % only if the corresponding channel is not found
325
                        % find corresponding channel
326 327 328 329 330 331 332
%                         coordComp = thetaPhi([1:iCoord-1 iCoord+1:coord.nPoints],:);
%                         diffCoord = bsxfun(@minus,coordCurrent,coordComp)== 0;
%                         idxCoord =  find(diffCoord(:,1)==1 & diffCoord(:,2) ==1);
                        diffCoord = bsxfun(@minus,coordCurrent,thetaPhi)== 0;
                        idxCoord =  find(diffCoord(:,1)==1 & diffCoord(:,2) ==1);
                        idxCoord =  idxCoord(idxCoord~=iCoord);
                        
333
                        if length(idxCoord) > 1
334
                            %                             deletedChannel = deletedChannel + length(idxCoord) -1;
335 336
                            idxCoord = idxCoord(1);
                        end
337
                        
338
                        % store the corresponding channel
339 340 341 342 343 344 345
                        pairs(counter,1) = iCoord;
%                         if idxCoord <iCoord
%                             pairs(counter,2) = idxCoord;
%                         else
%                             pairs(counter,2) = idxCoord+1;
%                         end
                        pairs(counter,2) = idxCoord;
346 347 348
                        counter = counter+1;
                    end
                    % break if all corresponding channels are found
349 350
                    if all(pairs(:))
                        break;
351 352 353 354 355 356 357 358
                    end
                end
                % ........................................................
                
                % split data in right and left channel
                idxLeft = pairs(:,1); % odd number
                idxRight = pairs(:,2);  % even number
                numNewChannels = length(pairs)*2;
359
                this.samplingRate = HRTFc.samplingRate;
360
                
361 362 363 364 365 366 367 368 369 370 371 372 373 374
                switch HRTFc.domain
                    case 'time'
                        this.domain = 'time';
                        this.timeData = zeros(HRTFc.nSamples, numNewChannels);
                        this.timeData(:,1:2:numNewChannels) = HRTFc.timeData(:,idxLeft);
                        this.timeData(:,2:2:numNewChannels) = HRTFc.timeData(:,idxRight);
                    case 'freq'
                        this.domain = 'freq';
                        this.freqData = zeros(HRTFc.nBins, numNewChannels);
                        this.freqData(:,1:2:numNewChannels) = HRTFc.freqData(:,idxLeft);
                        this.freqData(:,2:2:numNewChannels) = HRTFc.freqData(:,idxRight);
                    otherwise
                        error('Input data has unknown domain')
                end
375 376 377 378 379 380 381
                pairsT = pairs';
                this.channelCoordinates = HRTFc.channelCoordinates.n(pairsT(:));
                this.mEarSide = repmat(['L'; 'R'],numNewChannels/2, 1);
                
                % store coordinates
                this.mDirCoord = this.channelCoordinates.n(1:2:numNewChannels);
                this.signalType = 'energy';
382
                
383 384
                % channelnames coordinates
                this.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
385 386 387
                                          this.mEarSide ,...
                                          this.channelCoordinates.theta_deg,...
                                          this.channelCoordinates.phi_deg);
388 389 390
            end
        end
        
391 392 393
        function this = set.openDAFF2itaHRTF( this, daff_file_path )
            
            try_daff_old_version = false;
394
            metadata=[];
395 396 397 398
            % First try new version (v17)
            try
                handleDaff = DAFFv17( 'open', daff_file_path );
                props = DAFFv17( 'getProperties', handleDaff);
399
                
400 401 402
                counter = 1;
                data = zeros(props.filterLength,props.numRecords*2,'double' ) ;
                coordDaff = zeros(props.numRecords,2) ;
403
                
404 405 406 407 408
                for iDir = 1:props.numRecords
                    data(:,[counter counter+1]) = DAFFv17( 'getRecordByIndex', handleDaff,iDir )';
                    coordDaff(iDir,:) = DAFFv17( 'getRecordCoords', handleDaff, 'data', iDir )';
                    counter= counter+2;
                end
409
                
410
                metadata = DAFFv17('getMetadata', handleDaff);
411
                
412 413 414
            catch
                disp( 'Could not read DAFF file right away, falling back to old version and retrying ...' );
                try_daff_old_version = true;
415
            end
416
            
417 418 419 420
            if try_daff_old_version
                % Old version (v15)
                handleDaff = DAFFv15( 'open',daff_file_path);
                props = DAFFv15( 'getProperties', handleDaff);
421
                
422 423 424
                counter = 1;
                data = zeros(props.filterLength,props.numRecords*2,'double' ) ;
                coordDaff = zeros(props.numRecords,2) ;
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
                                
                tempMetadata = DAFFv15('getMetadata', handleDaff);
                
                % Convert old-style metadata format to v17.
                names = fieldnames( tempMetadata );
                for k = 1:numel( tempMetadata )
                    switch class(tempMetadata.(names{k}))
                        case 'logical'
                            datatype='bool';
                        case 'char'
                            datatype='string';
                        case 'double'
                            if rem(tempMetadata.(names{k}),1)==0
                                datatype='int';
                            else
                                datatype='float';
                            end
                    end
                    metadata = daffv17_add_metadata( metadata,cell2mat(names(k)),datatype,tempMetadata.(names{k}) );
                end
                
446 447 448 449 450 451
                for iDir = 1:props.numRecords
                    data(:,[counter counter+1]) = DAFFv15( 'getRecordByIndex', handleDaff,iDir )';
                    coordDaff(iDir,:) = DAFFv15( 'getRecordCoords', handleDaff, 'data', iDir )';
                    counter= counter+2;
                end
            end
452
            
453
            % Proceed (version independent)
454 455 456
            phiM = coordDaff(:,1)*pi/180;
            %phiM = mod(coordDaff(:,1),360)*pi/180;
            %if ~isempty(find(0<coordDaff(:,2),1,'first'))
457 458 459
            thetaM = mod(180-(coordDaff(:,2)),180)*pi/180;
%             thetaM = coordDaff(:,2)*pi/180;

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            %else
            %    thetaM = coordDaff(:,2)*pi/180;
            %end
            radius = ones(props.numRecords,1);

            chCoord = itaCoordinates;
            chCoord.sph = ones(size(data,2),3);

            chCoord.phi(1:2:2*props.numRecords) = phiM;
            chCoord.phi(2:2:2*props.numRecords) = phiM;
            chCoord.theta(1:2:2*props.numRecords) = thetaM;
            chCoord.theta(2:2:2*props.numRecords) = thetaM;

            this.mMetadata = metadata;
            this.data = data;
            this.mDirCoord = itaCoordinates([radius thetaM phiM],'sph');
            this.channelCoordinates = chCoord;
            this.mEarSide = repmat(['L'; 'R'],props.numRecords, 1);
            this.signalType = 'energy';
            % channelnames coordinates
            this.channelNames = ita_sprintf('%s ( %2.0f, \\theta= %2.0f)',...
                this.mEarSide ,   this.channelCoordinates.theta_deg,  this.channelCoordinates.phi_deg);

        end
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            
            function this = set.init(this,var)
                % TO DO !!!!!!!!!!!!!!!!!!!!!!!!!!!
                % Make it nicer and combine it with itaAudio2itaHRTF!!!
                % TO DO !!!!!!!!!!!!!!!!!!!!!!
                
                coord = var{find(strcmp(var,'dirCoord')==1)+1};
                this.domain = 'time';
                nSamples = var{find(strcmp(var,'nSamples')==1)+1};
                this.data = zeros(nSamples ,coord.nPoints*2);
                this.channelCoordinates.sph(1:2:coord.nPoints*2,:) = coord.sph;
                this.channelCoordinates.sph(2:2:coord.nPoints*2,:) = coord.sph;
                this.mEarSide = repmat(['L'; 'R'],coord.nPoints, 1);
                
                this.signalType = 'energy';
                % channelnames coordinates
                this.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
                    this.mEarSide , ...
                    this.channelCoordinates.theta_deg,this.channelCoordinates.phi_deg );
503
            end
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
            
            function this = set.hdf2itaHRTF(this,pathHDF5)
                handleHDF5 = itaHDF5(pathHDF5);
                
                names  = fieldnames(handleHDF5);
                HRTF   = handleHDF5.(names{4});
                
                dataHDF5 = HRTF.get_time;
                
                data = zeros(size(dataHDF5,1),HRTF.coordinates.nPoints*2);
                data(:,1:2:HRTF.coordinates.nPoints*2) = dataHDF5(:,:,1);
                data(:,2:2:HRTF.coordinates.nPoints*2) = dataHDF5(:,:,2);
                
                chCoord     = itaCoordinates;
                chCoord.sph = ones(HRTF.coordinates.nPoints*2,3);
                
                chCoord.phi(1:2:2*HRTF.size_time(2))   = HRTF.coordinates.phi;
                chCoord.phi(2:2:2*HRTF.size_time(2))   = HRTF.coordinates.phi;
                chCoord.theta(1:2:2*HRTF.size_time(2)) = HRTF.coordinates.theta;
                chCoord.theta(2:2:2*HRTF.size_time(2)) = HRTF.coordinates.theta;
                
                radius = ones(HRTF.coordinates.nPoints,1);
                
                this.data = data;
                this.mDirCoord = itaCoordinates([radius HRTF.coordinates.theta HRTF.coordinates.phi],'sph');
                this.channelCoordinates = chCoord;
                this.mEarSide = repmat(['L'; 'R'],HRTF.size_time(2), 1);
                this.signalType = 'energy';
                
                % channelnames coordinates
                this.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
                    this.mEarSide , ...
                    this.channelCoordinates.theta_deg, this.channelCoordinates.phi_deg);
537
            end
538 539 540
            
            
            function this = set.sofa2itaHRTF(this,pathFile)
541 542 543 544
                %% check if sofa is installed
                if ~exist('SOFAstart.m','file')
                    error('SOFA not installed. Run ita_sofa_install');
                end
545 546 547
                if ~exist(pathFile,'file')
                    f=filesep;
                    pathFile=[SOFAdbPath f 'SOFA' f pathFile];
548
                end
549 550 551 552 553 554 555 556
                handleSofa = SOFAload(pathFile);
                
                % get the number of measurement positions
                numPositions = length(handleSofa.SourcePosition);
                
                
                % data
                % the data is saved as positions x channel x filterdata
Jan-Gerrit Richter's avatar
bugfix:  
Jan-Gerrit Richter committed
557
                this.samplingRate = handleSofa.Data.SamplingRate;
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
                
                data = zeros(size(handleSofa.Data.IR,3),numPositions*2);
                data(:,1:2:numPositions*2) = squeeze(handleSofa.Data.IR(:,1,:)).';
                data(:,2:2:numPositions*2) = squeeze(handleSofa.Data.IR(:,2,:)).';
                
                % coordinates
                
                coordinates = ita_sofa_getCoordinates(handleSofa,'channelCoordinateType','SourcePosition');
                
                % duplicate the coordinates for both channels
                channelCoordinates = itaCoordinates(numPositions*2);
                channelCoordinates.x(1:2:numPositions*2) = coordinates.x;
                channelCoordinates.x(2:2:numPositions*2) = coordinates.x;
                channelCoordinates.y(1:2:numPositions*2) = coordinates.y;
                channelCoordinates.y(2:2:numPositions*2) = coordinates.y;
                channelCoordinates.z(1:2:numPositions*2) = coordinates.z;
                channelCoordinates.z(2:2:numPositions*2) = coordinates.z;
                
                
                % added view and up vector
                this.objectViewVector = itaCoordinates(handleSofa.ListenerView);
                this.objectUpVector = itaCoordinates(handleSofa.ListenerUp);
                this.objectCoordinates = itaCoordinates(handleSofa.ListenerPosition);
                warning('ITA_HRTF: Sofa Up and View vectors are ignored');
                this.data = data;
                this.channelCoordinates = channelCoordinates;
                this.mDirCoord = coordinates;
                this.mEarSide = repmat(['L'; 'R'],numPositions, 1);
                this.signalType = 'energy';
                
                
                this.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
                    this.mEarSide ,...
                    this.channelCoordinates.theta_deg, this.channelCoordinates.phi_deg );
                
                
                %% user data
                userDataFields = {'GLOBAL_Conventions','GLOBAL_Version','GLOBAL_SOFAConventions','GLOBAL_SOFAConventionsVersion' ...
                    ,'GLOBAL_APIName','GLOBAL_APIVersion','GLOBAL_ApplicationName','GLOBAL_ApplicationVersion','GLOBAL_AuthorContact' ...
                    ,'GLOBAL_Comment','GLOBAL_DataType','GLOBAL_History','GLOBAL_License','GLOBAL_Organization','GLOBAL_References' ...
                    ,'GLOBAL_RoomType','GLOBAL_Origin','GLOBAL_DateCreated','GLOBAL_DateModified','GLOBAL_Title','GLOBAL_DatabaseName' ...
                    ,'GLOBAL_RoomDescription','GLOBAL_ListenerShortName','API','ListenerPosition','ListenerPosition_Type','ListenerPosition_Units'...
                    ,'EmitterPosition','EmitterPosition_Type','EmitterPosition_Units','RoomCornerA','RoomCornerA_Type','RoomCornerA_Units' ...
                    ,'RoomCornerB','RoomCornerB_Type','RoomCornerB_Units','','','','','','',''};
                
                
                for index = 1:length(userDataFields)
                    if isfield(handleSofa,userDataFields{index})
                        userData.(userDataFields{index}) =  handleSofa.(userDataFields{index});
607 608
                    end
                end
609
                this.userData = userData;
610 611 612
            end
            
            
613
            %% .......................SET......................................
614
            
615 616 617 618 619 620
            function this = set.dirCoord(this,dirCoord)
                if isa(dirCoord,'itaCoordinates')
                    this.mDirCoord = dirCoord;
                    this.channelCoordinates.sph(1:2:end,:) = dirCoord.sph;
                    this.channelCoordinates.sph(2:2:end,:) = dirCoord.sph;
                end
621 622
            end
            
623 624 625 626
            function this = set.EarSide(this,Side)
                if sum(uint16(Side) == uint16('L') | uint16(Side) == uint16('R')) ==numel(Side)
                    this.mEarSide = Side;
                end
627 628
            end
            
629 630 631 632
            function this = set.TF_type(this,type)
                TF_types = this.propertiesTF_type;
                if sum(strcmpi(type, TF_types))==1
                    this.mTF_type = TF_types{strcmpi(type, TF_types)};
633 634
                end
            end
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
            
            %% ......................FUNCTIONS.................................
            
            %% Functions of this class
            function HRTFout = findnearestHRTF(this,varargin)
                if nargin ==2
                    coordC = varargin{1};
                    if isa(coordC, 'itaCoordinates') && this.dirCoord.nPoints~=0
                        coordC.r = ones(coordC.nPoints,1)*mean(this.dirCoord.r); % use the existing radius
                    else
                        error('itaHRTF:Def', ' Input must be itaCoordinates or HRTF has no coordinates.')
                    end
                else % rbo mode (theta,phi)
                    thetaC = deg2rad(varargin{1});
                    phiC = deg2rad(varargin{2});
                    r = ones(numel(phiC)*numel(thetaC),1)*mean(this.mDirCoord.r);
                    
                    if numel(thetaC)~=1 && numel(phiC)==1,
                        phiC = ones(numel(thetaC),1)*phiC;
                        if size(thetaC,2)>1,
                            thetaC = thetaC';
                        end
                    elseif numel(thetaC)==1 && numel(phiC)~=1,
                        thetaC = ones(numel(phiC),1)*thetaC;
                        if size(phiC,2)>1,
                            phiC = phiC';
                        end
                    end
                    coordC = itaCoordinates([r thetaC phiC],'sph');
664 665
                end
                
666
                idxCoord = this.dirCoord.findnearest(coordC);
667
                
668 669
                [~, I] = unique(idxCoord);
                idxCoordUnique = idxCoord(I);
670
                
671 672 673
                % idxCoordUnique = unique(idxCoord,'stable');
                if numel(idxCoord)~= numel(idxCoordUnique)
                    ita_verbose_info('Multiple coordinates are neglected!', 0);
674 675
                end
                
676 677 678 679 680 681 682 683 684
                if sum(this.EarSide == 'R') ~= sum(this.EarSide == 'L') % only one ear is available
                    ita_verbose_info('You use only one Ear! Conversion to itaAudio.', 0);
                    idxCoord = this.channelCoordinates.findnearest(coordC);
                    [~, I] = unique(idxCoord);
                    idxCoordUnique = idxCoord(I);
                    HRTFout = this.ch(idxCoordUnique).itaHRTF2itaAudio;
                else
                    HRTFout = this.direction(idxCoordUnique);
                end
685
                
686
                %HRTFout = this.direction(idxCoord);
687 688
            end
            
689 690 691 692
            function this = buildsearchdatabase(this)
               this.dirCoord = this.dirCoord.build_search_database; 
            end
            
693
            function obj = direction(this, idxCoord)
694 695 696 697 698 699 700 701
                %return the HRTF (L&R) for a/multiple given direction indices
                %   hOut = hObj.direction(idxCoord)
                %       
                %       idxCoord: index of the direction in hObj.dirCoord
                %
                %           hOut: HRTF in given direction    
                %
                % see also: hObj.findnearestHRTF
702 703 704 705 706 707 708 709 710
                idxDir = zeros(numel(idxCoord)*2,1);
                idxDir(1:2:numel(idxCoord)*2,:) = 2*idxCoord-1;
                idxDir(idxDir==0)=1;
                idxDir(2:2:numel(idxCoord)*2) = idxDir(1:2:numel(idxCoord)*2,:)+1;
                
                hrtfTMP = this.ch(idxDir);
                hrtfTMP.channelCoordinates = this.channelCoordinates.n(idxDir);
                hrtfTMP.EarSide = this.EarSide(idxDir);
                obj = itaHRTF(hrtfTMP);
711 712
            end
            
713
            function thetaUni = theta_Unique(this,varargin)
714
                thetaUni = uniquetol(this.dirCoord.theta);
715 716 717 718
                if nargin == 2
                    thetaUni = unique(this.dirCoord.theta,'stable');
                end
            end
719
            
720
            function phiUni = phi_Unique(this,varargin)
721
                phiUni = uniquetol(this.dirCoord.phi);
722 723 724 725
                if nargin == 2
                    phiUni = unique(this.dirCoord.phi,'stable');
                end
            end
726
            
727
            function thetaUni = theta_UniqueDeg(this,varargin)
728
                thetaUni = rad2deg(theta_Unique(this,varargin{:}));
729
            end
730
            
731
            function phiUni = phi_UniqueDeg(this,varargin)
732
                phiUni = rad2deg(phi_Unique(this,varargin{:}));
733
            end
734
            
735
            function slice = sphericalSlice(this,dirID,dir_deg,exactSearch)
736 737
                % dir in degree
                % dirID [phi, theta]
738 739 740
                if ~exist('exactSearch','var')
                    exactSearch = 0;
                end
741
                
742 743 744
                if ~exactSearch
                    phiU = rad2deg(this.phi_Unique);
                    thetaU = rad2deg(this.theta_Unique);
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
745 746 747 748 749 750
                    switch dirID
                        case {'phi_deg', 'p'}
                            slice = this.findnearestHRTF(thetaU,dir_deg);
                        case {'theta_deg', 't'}
                            slice = this.findnearestHRTF(dir_deg,phiU);
                    end
751 752 753 754
                else
                    earCoords = this.getEar('L').channelCoordinates;
                    switch dirID
                        case {'phi_deg', 'p'}
755
                            phiValues = uniquetol(earCoords.phi_deg);
756 757 758 759 760 761 762
                            [~,index] = min(abs(phiValues - dir_deg));
                            exactPhiValue = phiValues(index);
                            tmp = earCoords.n(earCoords.phi_deg == exactPhiValue);
                            thetaU = tmp.theta_deg;
                            
                            slice = this.findnearestHRTF(thetaU,dir_deg);
                        case {'theta_deg', 't'}
763
                            thetaValues = uniquetol(earCoords.theta_deg);
764 765 766 767 768 769 770
                            [~,index] = min(abs(thetaValues - dir_deg));
                            exactThetaValue = thetaValues(index);
                            tmp = earCoords.n(earCoords.theta_deg == exactThetaValue);
                            phiU = tmp.phi_deg;
                            
                            slice = this.findnearestHRTF(dir_deg,phiU);
                    end
771
                end
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
772

773
            end
774
            
775 776 777
            function slice = ss(this,dirID,dir_deg)
                slice = this.sphericalSlice(dirID,dir_deg);
            end
778
            
779 780 781 782 783 784 785 786 787
            function HRTFout = getEar(this,earSide)
                switch earSide
                    case 'L',
                        HRTFout = this.ch(this.EarSide	== 'L');
                        HRTFout.mEarSide = repmat('L',HRTFout.nChannels,1);
                    case 'R',
                        HRTFout = this.ch(this.EarSide == 'R');
                        HRTFout.mEarSide = repmat('R',HRTFout.nChannels,1);
                end
788 789
            end
            
790 791 792 793 794 795 796 797 798 799
            %% ITA Toolbox Functions
            function stimuli = conv(this,stimulus)
                if isa(stimulus, 'itaAudio')
                    stimuli = itaAudio(this.nDirections,1);
                    idxCh = 1:2:this.dimensions;
                    for idxDir = 1:this.nDirections
                        stimuli(idxDir) = ita_convolve(stimulus,this.ch([idxCh(idxDir) idxCh(idxDir)+1]));
                    end
                end
            end
800
            
801 802
            function play_gui(this,stimulus)
                if isa(stimulus, 'itaAudio')
803
                    
804 805 806 807 808
                    % check size of input data
                    if this.nDirections>75,
                        thisTmp = this.direction(1:75);
                        ita_verbose_info(' A lot of data ... you cannot show everything in the GUI!', 0);
                    else thisTmp = this;
809 810
                    end
                    
811 812
                    % convolve
                    stimuli = thisTmp.conv(stimulus);
813
                    
814 815 816 817
                    % normalize level
                    stimuliAll = stimuli.merge;
                    maxLevel =  max(abs(stimuliAll.timeData(:)))*1.05;
                    stimuliNorm = stimuli;
818
                    
819 820
                    for idxDir = 1:thisTmp.nDirections
                        stimuliNorm(idxDir) = stimuli(idxDir)/maxLevel;
821 822
                    end
                    
823
                    % play gui
824
                    
825 826 827 828 829
                    ita_play_gui(stimuliNorm, thisTmp.channelNames(1:2:thisTmp.dimensions));
                    %ita_play_gui(stimuliNorm, ita_sprintf('phi= %2.0f� theta= %2.0f�',...
                    %    thisTmp.dirCoord.phi_deg,thisTmp.dirCoord.theta_deg));
                end
                
830 831
            end
            
832 833 834 835 836 837 838 839 840 841 842 843
            function audioHRTF = itaHRTF2itaAudio(this)
                audioHRTF                       = itaAudio;
                audioHRTF.samplingRate          = this.samplingRate;
                audioHRTF.timeData              = this.timeData;
                audioHRTF.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
                    this.mEarSide , this.channelCoordinates.theta_deg,this.channelCoordinates.phi_deg );
                
                audioHRTF.channelCoordinates    = this.channelCoordinates;
                audioHRTF.signalType            = 'energy';
            end
            
            function surf(varargin)
Jan-Gerrit Richter's avatar
...  
Jan-Gerrit Richter committed
844
                sArgs  = struct('pos1_data','itaHRTF', 'earSide', 'L', 'freq' , 1000,'type','directivity','log',0);
845
                [this,sArgs,unused]   = ita_parse_arguments(sArgs,varargin);
846 847 848
                
                idxF = this.freq2index(sArgs.freq);
                
849 850
                if ~(~isempty(unused) && find(strcmp(unused,'parent')))
                    position = get(0,'ScreenSize');
851
                    figure('units','normalized','outerposition',[0 0 1 1]);
852
                end
853 854 855 856 857
                if sArgs.log 
                    freqData_dB = this.getEar(sArgs.earSide).freqData_dB;
                else
                    freqData_dB = this.getEar(sArgs.earSide).freqData;
                end
858 859
                switch sArgs.type
                    case 'directivity'
860
                        surf(this.dirCoord,freqData_dB(idxF,:),unused{:});
861 862
                        c = colorbar; ylabel(c,'Magnitude in dB')
                    case 'sphere'
863
                        surf(this.dirCoord,this.dirCoord.r,freqData_dB(idxF,:),unused{:});
864 865 866
                        c = colorbar;ylabel(c,'Magnitude in dB')
                    case 'phase'
                        phase = unwrap(angle(this.getEar(sArgs.earSide).freqData(idxF,:)));
867
                        surf(this.dirCoord,freqData_dB(idxF,:),phase,unused{:});
868
                        c = colorbar;ylabel(c,'Phase in rad')
869
                end
870
                title([sArgs.earSide ', f = ' num2str(round(this.freqVector(idxF)/100)/10) ' kHz'])
871 872
            end
            
873
            function display(this)
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
                if numel(this) == 0
                    disp('****** nothing to do, empty object ******')
                elseif numel(this) > 1
                    disp(['size(' inputname(1) ') = [' num2str(size(this))  ']; (for full display, pick a single instance)']);
                else
                    this.displayLineStart
                    this.disp
                    
                    dir = num2str(this.nDirections,5);
                    stringD = [dir ' Directions (Type = ' this.mTF_type ')'];
                    
                    middleLine = this.LINE_MIDDLE;
                    middleLine(3:(2+length(stringD))) = stringD;
                    fprintf([middleLine '\n']);
                end
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
                
            end
            
            function disp(this)
                
                disp@itaAudio(this)
                
                sphType = [this.sphereType repmat(' ',1,9-length(this.sphereType))];
                string = ['      Sphere Type   = ' sphType ];
                
                % this block adds the class name
                classnamestring = ['^--|' mfilename('class') '|'];
                fullline = repmat(' ',1,this.LINE_LENGTH);
                fullline(1:numel(string)) = string;
                startvalue = length(classnamestring);
                fullline(length(fullline)-startvalue+1:end) = classnamestring;
                disp(fullline);
                
                % end line
908 909
            end
            
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
            %% Ramonas' Functions
            
            function varargout = ITD(varargin)
                % -----------------------------------------------------------------
                % See methods and options below
                % -----------------------------------------------------------------
                % Input
                sArgs  = struct('pos1_data','itaHRTF', 'method', 'phase_delay', 'filter' , [200 2000] ,...
                    'thresh','10dB','energy',true,'centroid',false,'reshape',true);
                [this,sArgs]   = ita_parse_arguments(sArgs,varargin);
                
                if numel(this.theta_Unique)>1
                    ita_verbose_info(' More than one elevation in this object!', 0);
                    %this = this.sphericalSlice('theta_deg',90);
                end
                
                % -------------------------------------------------------------
                % methods: phase_delay, xcorr, threshold
                % -------------------------------------------------------------
                % Katz, Brian F. G.; Noisternig, Markus (2014): A comparative
                % study of interaural time delay estimation methods. In: The
                % Journal of the Acoustical Society of America 135 (6), S.
                % 3530-3540.
                
                switch sArgs.method
                    case 'phase_delay'
                        % .....................................................
                        % options: filter
                        % .....................................................
                        [~,tau] = ita_time_shift(this,'0dB');
                        [~,idxMin] = max(tau); % shift of trackLength/3 seems to be good for plotting - No idea
                        thisC = ita_time_shift(this,tau(idxMin)-this.trackLength/3,'time');
                        
                        if ischar(sArgs.filter) % frequency dependent
                            p1 = thisC.freqData(:,1:2:thisC.dimensions);
                            p2 = thisC.freqData(:,2:2:thisC.dimensions);
                            
                            phase1 = unwrap(angle(p1));
                            phase2 = unwrap(angle(p2));
                            phasenDiff = phase1 - phase2;
                            
                            ITD = phasenDiff./(2*pi*repmat(thisC.freqVector,1,size(phase1,2)));
                        else % averaged
953
                            usedBins = thisC.freq2index(sArgs.filter(1)):thisC.freq2index(sArgs.filter(2));
954
                            phase = unwrap(angle(thisC.freqData(3:end,:)));
955
                            freqVector = thisC.freqVector;
956
                            t0_freq = bsxfun(@rdivide, phase,2*pi*freqVector(3:end));
957
                            t0_freq = t0_freq(~isnan(t0_freq(:,1)),:);
958
                            t0_mean = mean(t0_freq(3+usedBins,:)); %mean is smoother than max; lower freq smooths also the result
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
                            ITD =  t0_mean(thisC.EarSide == 'L') - t0_mean(thisC.EarSide == 'R');
                        end
                    case 'xcorr'
                        % .....................................................
                        % options: energy, filter, centroid
                        % .....................................................
                        if ischar(sArgs.filter),  thisF = this; % FILTER
                        else thisF = ita_mpb_filter(this,[sArgs.filter(1), sArgs.filter(2)]);
                        end
                        
                        % Interpolation for smoother curves
                        xUpSample = 5;
                        SR = xUpSample*thisF.samplingRate;
                        tV_Interp = 0:1/SR:thisF.trackLength;
                        timeData_Interp = interp1(thisF.timeVector,thisF.timeData,tV_Interp,'spline');
                        
                        % case: energy
                        if sArgs.energy ,timeData_Interp  = timeData_Interp.^2;
                        end
                        
                        idxL = find(thisF.EarSide== 'L'); idxR = find(thisF.EarSide == 'R');
                        corrIR = zeros(2*numel(tV_Interp)-1,this.nDirections);
                        for idxDir = 1:thisF.nDirections
                            corrIR(:,idxDir) =  xcorr(timeData_Interp(:,idxL(idxDir)),timeData_Interp(:,idxR(idxDir)));
                        end
                        
                        if ~sArgs.centroid      % max
                            [~, idxMax] =  max(abs(corrIR));
                            ITD  = (numel(tV_Interp)- idxMax)/SR;
                        else                    % centroid
                            tV = 0:1/SR:(2*numel(tV_Interp)-2)/SR;
                            C = sum(bsxfun(@times,abs(corrIR),tV'))./sum(abs(corrIR));
                            ITD = thisF.trackLength-C;
                        end
                    case 'threshold'
                        % .....................................................
                        % options: filter
                        % .....................................................
                        if ischar(sArgs.filter),  thisF = this; % FILTER
                        else thisF = ita_mpb_filter(this,[sArgs.filter(1), sArgs.filter(2)]);
                        end
                        
                        [~,tau] = ita_time_shift(thisF,sArgs.thresh);
                        ITD = tau(thisF.EarSide== 'L')-tau(thisF.EarSide == 'R');
                end
                
                % Reshape the ITD in a matrix where the column defines the phi-
                % direction and the row the theta-direction
                if sArgs.reshape && ~ischar(sArgs.filter)
                    nPhi    = numel(this.phi_Unique);
                    nTheta  = numel(this.theta_Unique);
                    if nPhi*nTheta == this.nDirections
                        sITD = reshape(ITD,nTheta,nPhi);
                    else
                        ita_verbose_info(' ITD could not be reshape: nPhi*nTheta ~= nDir!', 0);
                        sITD = ITD;
                    end
                else
                    sITD = ITD;
                end
                
                varargout{1} = sITD;
                if nargout == 2, varargout{2} = rad2deg(this.phi_Unique('stable'));
1022 1023
                end
            end
1024 1025 1026 1027 1028 1029
            
            function t0 = meanTimeDelay(this,varargin)
                %-- OLD -------------------------------------------------------
                [~,tau] = ita_time_shift(this,'0dB');
                [~,idxMin] = max(tau); % shift of trackLength/3 seems to be good for plotting - No idea
                thisC = ita_time_shift(this,tau(idxMin)-this.trackLength*0.33,'time');
1030
                
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
                phase = unwrap(angle(thisC.freqData));
                t0_freq = bsxfun(@rdivide, phase,2*pi*thisC.freqVector);
                %t0_mean = t0_freq(thisC.freq2index(1000),:);
                t0_mean = mean(t0_freq(thisC.freq2index(500):thisC.freq2index(2000),:)); %mean is smoother than max; lower freq smooths also the result
                if nargin==2
                    if strcmpi(varargin{1},'L')
                        t0 =  t0_mean(thisC.EarSide == 'L');
                    elseif strcmpi(varargin{1},'R')
                        t0 =  t0_mean(thisC.EarSide == 'R');
                    end
                else t0 =  t0_mean;
                end
1043
            end
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
            
            function varargout = calcDTF(this)
                if ~strcmpi(this.TF_type,'DTF')
                    [DTF,comm] = test_rbo_DTF_itaHRTF(this);
                    
                    varargout{1} =DTF;
                    if nargout ==2,varargout{2} = comm;end
                end
            end
            
1054
            this = interp(varargin);
1055 1056 1057 1058 1059
            %
            % Function to calculate HRTFs for arbitrary field points using a N-th order
            % spherical harmonics (SH) interpolation / range extrapolation, as described in [1],
            % SH expansion coefficients are calculated by means of a least-squares
            % approach with Tikhonov regularization
1060
            %
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
            % Function may also be used for spatial smoothing of HRTF using
            % the method described in [2]. As field input use the original
            % measurement grid and set the desired order of the SH matrix /
            % truncation order.
            %
            % INPUT:
            %     varargin{1}      ...  itaCoordinates object (required)
            %                           varargin{1}.phi: desired azimuth angles for HRTF interpolation [0 2*pi)
            %                           varargin{1}.theta: desired zenith angles for HRTF interpolation [0 pi]
            %                           varargin{1}.r: (optional) desired radius used for range extrapolation in [m],
            %                                    set to 1 if no range extrapolation is required
            %     order            ...  order of spherical harmonics matrix (default: 50)
            %     epsilon          ...  regularization coefficient (default: 1e-8)
            %
            % OUTPUT:
            %     itaHRTF object
            %     .freqData: interpolated / range-extrapolated HRTFs for defined field points
            %     .timeData: interpolated / range-extrapolated HRIRs for defined field points
            %     .dirCoord: itaCoordinates object
            %
            % Required: SphericalHarmonics functions of ITA Toolbox
            %
            % [1] Pollow, Martin et al., "Calculation of Head-Related Transfer Functions
            %     for Arbitrary Field Points Using Spherical Harmonics Decomposition",
            %     Acta Acustica united with Acustica, Volume 98, Number 1, January/February 2012,
            %     pp. 72-82(11)
            %
            % Author:  Florian Pausch <fpa@akustik.rwth-aachen.de>
            % Version: 2016-02-05
            
            
1092 1093
            this = reduce_spatial(this,coords,varargin);
            % Function to spatially reduce the HRTF. 
1094
            
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
            function this = smooth_linphase(this,varargin)
                % function this = smooth_linphase(varargin)
                %
                % Function to smooth HRTFs in the frequency domain based on the method proposed by Rasumov et al. in [3], complex smoothing
                % is done via ita_smooth()
                %
                % Parameters:
                % 'f_lin'       ... frequency above which the phase is approximated by a linear phase term
                % 'smoothtype'  ... smoothing method, 'LinTimeSec', 'LinTimeSamp', 'LinFreqHertz', 'LinFreqBins',
                %                                     'LogFreqOctave1' (default), 'LogFreqOctave2' or 'Gammatone'
                % 'windowWidth' ... bandwidth of filter (depends on smoothtype - type help ita_smooth), e.g. 1/9 (default) in frequency domain
                % 'dataTypes'   ... defines on which data type smoothing is applied, 'Real', 'Complex', 'Abs' (default), 'GDelay', 'Abs+GDelay'
                %                                                                    or 'Abs+Phase' (type help ita_smooth)
                %
                % [2] Rasumow, Eugen et al, "Smoothing individual head-related transfer functions in the frequency and spatial domains"
                % The Journal of the Acoustical Society of America, 135, 2012-2025 (2014), DOI:http://dx.doi.org/10.1121/1.4867372
                %
                % Author:  Florian Pausch <fpa@akustik.rwth-aachen.de>
                % Version: 2015-11-04
                
                sArgs         = struct('f_lin',5000,'smoothtype','LogFreqOctave1','windowWidth',1/9,'dataTypes','Abs');
                sArgs         = ita_parse_arguments(sArgs,varargin,1);
                f_lin         = sArgs.f_lin;                       % frequency above which the phase is approximated by a linear phase term (f_lin=5000, default)
                
                % parameters for ita_smooth()
                smoothtype    = sArgs.smoothtype;                  % smoothing method, 'LinTimeSec', 'LinTimeSamp', 'LinFreqHertz', 'LinFreqBins',
                % 'LogFreqOctave1' (default), 'LogFreqOctave2' or 'Gammatone'
                windowWidth   = sArgs.windowWidth;                 % bandwidth of filter (depends on smoothtype - type help ita_smooth), e.g. 1/9 (default) in frequency domain
                dataTypes     = sArgs.dataTypes;                   % 'Real', 'Complex', 'Abs' (default), 'GDelay', 'Abs+GDelay' or 'Abs+Phase' (type help ita_smooth)
                
                %% Step I: Estimation of the delay of the HRTF peak and the resulting linear phase
                %             HRTF_env      = ita_envelope(this);                      % calculate the envelope of the HRIR
                tau           = ita_start_IR(ita_mpb_filter(this,[200,10000]),'threshold',0,'correlation',true);
                tau           = tau/this.samplingRate;
                
                linphase      = exp( -1i*2*pi .* repmat(this.freqVector(this.freq2index(f_lin)+1:end)',1,this.nChannels).*...
                    repmat(tau,length(this.freqVector(this.freq2index(f_lin)+1:end)),1) );        % linear phase of evaluated HRTF set
                
                %% Step II: Linearize phase for f >= f_lin
                this.freqData = abs(this.freqData) .* [exp( 1i*angle(this.freqData(1:this.freq2index(f_lin),:)) );...
                    linphase ] ;
                
                %% Step III: Remove delay tau
                this          = ita_time_shift(this,-tau,'samples');
                
                %% Step IV: Complex smoothing
                this_smooth   = ita_smooth(this,smoothtype,windowWidth,dataTypes);
                this.timeData = this_smooth.timeData;
                
                %% Step V: Reconstruct delay tau
                this          = ita_time_shift(this,tau,'samples');
                
1147 1148
            end
            
1149 1150
            
            % JRI: isn't this the same as itaHRTF.interp? 
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
            function thisS = smooth_spatial(this, varargin)
                % function this = smooth_spatial(varargin)
                %
                % Function to smooth HRTFs in the spatial domain as shown in [3]
                %
                % Parameters
                %     'N'              ...  order of truncated spherical harmonics matrix (default: 4)
                %                           a lower order results in less spatial detail/high-frequency detail
                %                           in smoothed HRTF data set
                %     'epsilon'        ...  regularization coefficient (default: 1e-8)
                %
                % Required: SphericalHarmonics functions of ITA Toolbox
                %
                % [3] Romigh, G.D.; Brungart, D.S.; Stern, R.M.; Simpson, B.D., "Efficient Real Spherical Harmonic Representation of Head-Related
                % Transfer Functions," in Selected Topics in Signal Processing, IEEE Journal of , vol.9, no.5, pp.921-930, Aug. 2015
                % doi: 10.1109/JSTSP.2015.2421876
                %
                % Author:  Florian Pausch <fpa@akustik.rwth-aachen.de>
                % Version: 2016-02-12
                
                tic;
                
                sArgs   = struct('N',4,'epsilon',1e-8,'type','min');
                sArgs   = ita_parse_arguments(sArgs,varargin);
                N       = sArgs.N;
                epsilon = sArgs.epsilon;
                
                Nmeas   = floor(sqrt(this.nDirections/4)-1); % SH order of measurement grid (assuming equiangular grid)
                
                if N>Nmeas
                    fprintf('[\b[itaHRTF.smooth_spatial] Chosen SH order is too high. Order is set to maximum SH order of measurement grid!]\b\n')
                    fprintf('[\b[itaHRTF.smooth_spatial] N = Nmeas = %s (assuming equiangular sampling)]\b\n',num2str(Nmeas))
                    N=Nmeas;
                end
                
                %% Weighting + regularization
                regweights          = ita_sph_degreeorder2linear(0:Nmeas,0);      % construct vector of length (Nmeas+1) regularization weights
                regweights_rep      = zeros(sum(2*(0:Nmeas)'+1),1);
                regweights_rep(1)   = regweights(1);
                cntr                = 2;
                for n=1:Nmeas % repeat regularization weights to get a (Nmeas+1)^2 x 1 vector (TODO: more elegant solution needed)
                    nTimes                              = 2*n+1;
                    regweights_rep(cntr:cntr+nTimes-1)  = regweights(n+1)*ones(nTimes,1);
                    cntr                                = cntr + nTimes;
                end
                
                [~, vWeights]   = this.dirCoord.spherical_voronoi;         % calculate weighting coefficients (Voronoi surfaces <-> measurement points)
                W               = diag(vWeights);                                      % diagonal matrix containing weights
                D               = diag(regweights_rep);                                % decomposition order-dependent Tikhonov regularization
                
1201
                Y               = ita_sph_base(this.dirCoord,Nmeas,'real');   % calculate real-valued SHs using the measurement grid (high SH-order)
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
                
                %% Calculate spatially smoothed HRTF data set
                hrtf_smoo_wo_ITD = zeros(this.nBins,2*this.dirCoord.nPoints); % init.: columns: LRLRLR...
                for ear=1:2
                    % decompose logarithmic magnitude spectra of measured HRTF set into SH basis functions, as done in [3]
                    
                    switch sArgs.type
                        case 'complex'
                            freqData_temp   = this.freqData(:,ear:2:end);
                            a0              = (Y.'*W*Y + epsilon*D) \ Y.'*W * freqData_temp.';     % calculate weighted SH coefficients using a decomposition order-dependent Tikhonov regularization
                        otherwise
                            freqData_dB     = this.freqData_dB;
                            freqData_temp   = freqData_dB(:,ear:2:end);
                            a0              = (Y.'*W*Y + epsilon*D) \ Y.'*W * freqData_temp.';     % calculate weighted SH coefficients using a decomposition order-dependent Tikhonov regularization
                    end
                    Yest        = Y(:,1:(N+1)^2);                                    % eat first (N+1)^2 SH basis functions
                    a0_trunc    = a0(1:(N+1)^2,:);                               % reduce number of coefficients
                    hrtf_smoo_wo_ITD(:,ear:2:end) = (Yest*a0_trunc).';        % spatially smoothed HRTF due to reduction of SH decomposition order
                end
                
                %             % calculate magnitude spectrum and add original HRIR delays as linear phase component
                %             linphase = exp( -1i*2*pi * repmat(this.freqVector,1,this.nChannels).*...
                %                                        repmat(idxIRs_orig/this.samplingRate,this.nBins,1) );
                %             thisS = this;
                %             thisS.freqData = 10.^(hrtf_smoo_wo_ITD/20) .* linphase;
                
                
1229
                switch sArgs.type
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
                    case 'min'
                        this_minphase   = ita_minimumphase(this);
                        idxIRs_orig     = ita_start_IR(ita_mpb_filter(this,[200,2000]),'threshold',0,'correlation',true);
                        deltaT          = idxIRs_orig./this_minphase.samplingRate*1.3;
                        if min(deltaT)  < 0 % no negative shifts
                            deltaT      = deltaT-min(deltaT);
                        end
                        
                        thisMin         = this; %smoothed HRTF
                        thisMin.freqData= 10.^(hrtf_smoo_wo_ITD/20);
                        thisS           = test_rbo_FIR_lagrange_delay(deltaT,thisMin);
                        
                        %thisS           = ita_mpb_filter(thisS,[200 20000]);
                    case 'old'
                        oldPhase        = angle(this.freqData);% rbo test
                        thisS           = itaHRTF(this);
                        thisS.freqData  = 10.^(hrtf_smoo_wo_ITD/20) .* exp(1i.*oldPhase); %rbo test
                        
                        %thisS           = ita_mpb_filter(thisS,[200 20000]);
1249
                    case 'complex'
1250 1251
                        thisS = this;
                        thisS.freqData  = hrtf_smoo_wo_ITD; %rbo test
1252
                end
1253 1254 1255 1256 1257
                
                t2 = toc;
                
                fprintf(['[itaHRTF.smooth_spatial] Calculation finished after ',num2str(round(t2*100/60)/100),' min\n'])
                
1258 1259
            end
            
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
            
            % calculate diffuse field HRTF from data
            % taken from 
            % Equalization methods in binaural technology
            % Veronique Larcher et al
            function returnData = getDiffuseFieldHRTF(this)
                coords = this.getEar('L').channelCoordinates;
                [~,weights] = coords.spherical_voronoi;
                returnData = itaAudio;
                tmp(:,1) = sum(bsxfun(@times,abs(this.getEar('L').freqData).^2,weights.'),2)./(4*pi);
                tmp(:,2) = sum(bsxfun(@times,abs(this.getEar('R').freqData).^2,weights.'),2)./(4*pi);
                returnData.freqData = tmp;
                
                returnData.signalType = 'power';
                returnData.channelNames = {'Left Ear','Right Ear'};
                returnData.comment = 'Diffuse Field HRTF';
            end
           
            
            
1280
            %% Plot
1281
            
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
            function plot_ITD(varargin)
                % init
                sArgs  = struct('pos1_data','itaHRTF', 'method', 'phase_delay', 'filter' , [200 2000] ,...
                    'thresh','10dB','energy',true,'centroid',false,'reshape',true,...
                    'theta_deg',[],'plot_type','color');
                [this,sArgs]   = ita_parse_arguments(sArgs,varargin);
                
                % calculate ITD
                if ~isempty(sArgs.theta_deg)
                    thisS = this.sphericalSlice('theta_deg',sArgs.theta_deg);
                else thisS = this;
                end
                
                thetaC_deg  = rad2deg(thisS.theta_Unique);
1296
                phiC_deg    = sort(mod(rad2deg(thisS.phi_Unique),360));
1297 1298
                nTheta      = numel(thetaC_deg);
                nPhi        = numel(phiC_deg);
1299
                coord       = reshape(mod(thisS.dirCoord.phi_deg,360),nTheta,nPhi);
1300
                [~, idxC]   = sort(coord,2);
1301
                [~, idxCT]  = uniquetol(thisS.dirCoord.theta_deg,eps);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
                
                ITD    = thisS.ITD('method',...
                    sArgs.method, 'filter' , sArgs.filter , 'thresh',sArgs.thresh,...
                    'energy',sArgs.energy,'centroid',sArgs.centroid,'reshape',true);
                
                ITD_S = ITD;
                for idxT = 1:nTheta
                    ITD_S(idxT,:) = ITD(idxT,idxC(idxT,:));
                end
                ITD_SS = ITD_S(idxCT(1:nTheta),:);
                
                %..............................................................
                % create figure
                position = get(0,'ScreenSize');
                figure
                set(gcf,'Position',[10 50 position(3:4)*0.85]);
                if strcmp(sArgs.method,'phase_delay') && ischar(sArgs.filter) % frequency dependent ITD
                    pcolor(phiC_deg,this.freqVector,ITD)
                    title(strcat('\phi = ', num2str(round(thetaC_deg)), '�'))
                    shading flat
                    colorbar
                    
                    ylabel('frequency');
                    ylim([this.freqVector(1)  this.freqVector(end)])
                    xlabel('azimuth angle');
                    set(gca, 'YScale', 'log');
1328
                    
1329 1330
                    [xticks, xlabels] = ita_plottools_ticks('log');
                    set(gca,'yTick',xticks,'yticklabel',xlabels)
1331
                    
1332 1333
                    cMax = max(max(ITD(2:end,:)));
                    cMin = abs(min(min(ITD(2:end,:))));
1334
                    
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
                    if cMax>cMin,caxis([-cMax cMax]);
                    else caxis([-cMin cMin]);
                    end
                elseif strcmp(sArgs.plot_type,'color') && numel(sArgs.theta_deg)~= 1
                    % angle dependent ITD (theta & phi)
                    pcolor(thetaC_deg, phiC_deg,ITD_SS'*1000)
                    shading flat
                    colorbar
                    cMax = max(abs(ITD_SS(:)));
                    caxis([-cMax cMax]*1100);
                    grid on
                    set(gca,'layer','top')
                    xlabel('Zenith Angle in Degree');
                    ylabel('Azimuth Angle in Degree');
                    set(gca,'xTick',0:15:360,'yTick',