itaHRTF.m 73.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] =  unique([this.channelCoordinates.phi_deg this.channelCoordinates.theta_deg] ,'rows');
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 281 282 283 284 285 286 287 288 289 290 291
        function this = set.itaAudio2itaHRTF(this,HRTF)
            if isa(HRTF,'itaAudio'),
                % Multi instance?
                if numel(HRTF)>1,
                    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 319 320 321 322 323 324 325 326 327 328
                end
                
                
                counter = 1;
                thetaPhi = round([coord.theta_deg coord.phi_deg]*10)/10;
                deletedChannel = 0;
                for i1 = 1:coord.nPoints
                    coordCurrent = thetaPhi(i1,:);
                    if isempty(find(pairs(:) == i1, 1)) % only if the corresponding channel is not found
                        % find corresponding channel
                        coordComp = thetaPhi([1:i1-1 i1+1:coord.nPoints],:);
                        diffCoord = bsxfun(@minus,coordCurrent,coordComp)== zeros(size(coordComp));
                        idxCoord =  find(diffCoord(:,1).*diffCoord(:,2) ==1);
                        if length(idxCoord) > 1
329
                            %                             deletedChannel = deletedChannel + length(idxCoord) -1;
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                            idxCoord = idxCoord(1);
                        end
                        % store the corresponding channel
                        pairs(counter,1) = i1;
                        if idxCoord <i1
                            pairs(counter,2) = idxCoord;
                        else
                            pairs(counter,2) = idxCoord+1;
                        end
                        counter = counter+1;
                    end
                    % break if all corresponding channels are found
                    if sum(pairs(:))== sum(1:coord.nPoints),break
                    end
                end
                % ........................................................
                
                % split data in right and left channel
                idxLeft = pairs(:,1); % odd number
                idxRight = pairs(:,2);  % even number
                numNewChannels = length(pairs)*2;
                this.data = zeros(HRTFc.nSamples, numNewChannels);
                this.data(:,1:2:numNewChannels) = HRTFc.timeData(:,idxLeft);
                this.data(:,2:2:numNewChannels) = HRTFc.timeData(:,idxRight);
                
                this.domain = 'time';
                pairsT = pairs';
                
                this.channelCoordinates = HRTFc.channelCoordinates.n(pairsT(:));
                this.mEarSide = repmat(['L'; 'R'],numNewChannels/2, 1);
                this.samplingRate = HRTFc.samplingRate;
                
                
                % store coordinates
                this.mDirCoord = this.channelCoordinates.n(1:2:numNewChannels);
                this.signalType = 'energy';
                % channelnames coordinates
                this.channelNames = ita_sprintf('%s ( %2.0f, %2.0f)',...
                    this.mEarSide ,...
                    this.channelCoordinates.theta_deg, this.channelCoordinates.phi_deg );
            end
        end
        
373 374 375
        function this = set.openDAFF2itaHRTF( this, daff_file_path )
            
            try_daff_old_version = false;
376
            metadata=[];
377 378 379 380
            % First try new version (v17)
            try
                handleDaff = DAFFv17( 'open', daff_file_path );
                props = DAFFv17( 'getProperties', handleDaff);
381
                
382 383 384
                counter = 1;
                data = zeros(props.filterLength,props.numRecords*2,'double' ) ;
                coordDaff = zeros(props.numRecords,2) ;
385
                
386 387 388 389 390
                for iDir = 1:props.numRecords
                    data(:,[counter counter+1]) = DAFFv17( 'getRecordByIndex', handleDaff,iDir )';
                    coordDaff(iDir,:) = DAFFv17( 'getRecordCoords', handleDaff, 'data', iDir )';
                    counter= counter+2;
                end
391
                
392
                metadata = DAFFv17('getMetadata', handleDaff);
393
                
394 395 396
            catch
                disp( 'Could not read DAFF file right away, falling back to old version and retrying ...' );
                try_daff_old_version = true;
397
            end
398
            
399 400 401 402
            if try_daff_old_version
                % Old version (v15)
                handleDaff = DAFFv15( 'open',daff_file_path);
                props = DAFFv15( 'getProperties', handleDaff);
403
                
404 405 406
                counter = 1;
                data = zeros(props.filterLength,props.numRecords*2,'double' ) ;
                coordDaff = zeros(props.numRecords,2) ;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
                                
                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
                
428 429 430 431 432 433
                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
434
            
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
            
            phiM = coordDaff(:,1)*pi/180;
            %phiM = mod(coordDaff(:,1),360)*pi/180;
            %if ~isempty(find(0<coordDaff(:,2),1,'first'))
            thetaM = coordDaff(:,2)*pi/180;
            %thetaM = mod(180-(coordDaff(:,2)+90),180)*pi/180;
            %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
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            
            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 );
484
            end
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
            
            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);
518
            end
519 520 521 522 523 524
            
            
            function this = set.sofa2itaHRTF(this,pathFile)
                if ~exist(pathFile,'file')
                    f=filesep;
                    pathFile=[SOFAdbPath f 'SOFA' f pathFile];
525
                end
526 527 528 529 530 531 532 533
                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
534
                this.samplingRate = handleSofa.Data.SamplingRate;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 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
                
                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});
584 585
                    end
                end
586
                this.userData = userData;
587 588 589
            end
            
            
590
            %% .......................SET......................................
591
            
592 593 594 595 596 597
            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
598 599
            end
            
600 601 602 603
            function this = set.EarSide(this,Side)
                if sum(uint16(Side) == uint16('L') | uint16(Side) == uint16('R')) ==numel(Side)
                    this.mEarSide = Side;
                end
604 605
            end
            
606 607 608 609
            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)};
610 611
                end
            end
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
            
            %% ......................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');
641 642
                end
                
643
                idxCoord = this.dirCoord.findnearest(coordC);
644
                
645 646
                [~, I] = unique(idxCoord);
                idxCoordUnique = idxCoord(I);
647
                
648 649 650
                % idxCoordUnique = unique(idxCoord,'stable');
                if numel(idxCoord)~= numel(idxCoordUnique)
                    ita_verbose_info('Multiple coordinates are neglected!', 0);
651 652
                end
                
653 654 655 656 657 658 659 660 661
                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
662
                
663
                %HRTFout = this.direction(idxCoord);
664 665
            end
            
666 667 668 669
            function this = buildsearchdatabase(this)
               this.dirCoord = this.dirCoord.build_search_database; 
            end
            
670 671 672 673 674 675 676 677 678 679
            function obj = direction(this, idxCoord)
                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);
680 681
            end
            
682
            function thetaUni = theta_Unique(this,varargin)
683
                thetaUni = uniquetol(this.dirCoord.theta,eps);
684 685 686 687
                if nargin == 2
                    thetaUni = unique(this.dirCoord.theta,'stable');
                end
            end
688
            
689
            function phiUni = phi_Unique(this,varargin)
690
                phiUni = uniquetol(this.dirCoord.phi,eps);
691 692 693 694
                if nargin == 2
                    phiUni = unique(this.dirCoord.phi,'stable');
                end
            end
695
            
696 697 698
            function thetaUni = theta_UniqueDeg(this,varargin)
                thetaUni = rad2deg(theta_Unique(this,varargin));
            end
699
            
700 701 702
            function phiUni = phi_UniqueDeg(this,varargin)
                phiUni = rad2deg(phi_Unique(this,varargin));
            end
703
            
704
            function slice = sphericalSlice(this,dirID,dir_deg,exactSearch)
705 706
                % dir in degree
                % dirID [phi, theta]
707 708 709
                if ~exist('exactSearch','var')
                    exactSearch = 0;
                end
710
                
711 712 713
                if ~exactSearch
                    phiU = rad2deg(this.phi_Unique);
                    thetaU = rad2deg(this.theta_Unique);
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
714 715 716 717 718 719
                    switch dirID
                        case {'phi_deg', 'p'}
                            slice = this.findnearestHRTF(thetaU,dir_deg);
                        case {'theta_deg', 't'}
                            slice = this.findnearestHRTF(dir_deg,phiU);
                    end
720 721 722 723
                else
                    earCoords = this.getEar('L').channelCoordinates;
                    switch dirID
                        case {'phi_deg', 'p'}
724
                            phiValues = uniquetol(earCoords.phi_deg);
725 726 727 728 729 730 731
                            [~,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'}
732
                            thetaValues = uniquetol(earCoords.theta_deg);
733 734 735 736 737 738 739 740
                            [~,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
                end
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
741

742
            end
743
            
744 745 746
            function slice = ss(this,dirID,dir_deg)
                slice = this.sphericalSlice(dirID,dir_deg);
            end
747
            
748 749 750 751 752 753 754 755 756
            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
757 758
            end
            
759 760 761 762 763 764 765 766 767 768
            %% 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
769
            
770 771
            function play_gui(this,stimulus)
                if isa(stimulus, 'itaAudio')
772
                    
773 774 775 776 777
                    % 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;
778 779
                    end
                    
780 781
                    % convolve
                    stimuli = thisTmp.conv(stimulus);
782
                    
783 784 785 786
                    % normalize level
                    stimuliAll = stimuli.merge;
                    maxLevel =  max(abs(stimuliAll.timeData(:)))*1.05;
                    stimuliNorm = stimuli;
787
                    
788 789
                    for idxDir = 1:thisTmp.nDirections
                        stimuliNorm(idxDir) = stimuli(idxDir)/maxLevel;
790 791
                    end
                    
792
                    % play gui
793
                    
794 795 796 797 798
                    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
                
799 800
            end
            
801 802 803 804 805 806 807 808 809 810 811 812
            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
813
                sArgs  = struct('pos1_data','itaHRTF', 'earSide', 'L', 'freq' , 1000,'type','directivity','log',0);
814
                [this,sArgs,unused]   = ita_parse_arguments(sArgs,varargin);
815 816 817
                
                idxF = this.freq2index(sArgs.freq);
                
818 819 820 821
                if ~(~isempty(unused) && find(strcmp(unused,'parent')))
                    position = get(0,'ScreenSize');
                    figure('Position',[10 50 position(3:4)*0.85]);
                end
822 823 824 825 826
                if sArgs.log 
                    freqData_dB = this.getEar(sArgs.earSide).freqData_dB;
                else
                    freqData_dB = this.getEar(sArgs.earSide).freqData;
                end
827 828
                switch sArgs.type
                    case 'directivity'
829
                        surf(this.dirCoord,freqData_dB(idxF,:),unused{:});
830 831
                        c = colorbar; ylabel(c,'Magnitude in dB')
                    case 'sphere'
832
                        surf(this.dirCoord,this.dirCoord.r,freqData_dB(idxF,:),unused{:});
833 834 835
                        c = colorbar;ylabel(c,'Magnitude in dB')
                    case 'phase'
                        phase = unwrap(angle(this.getEar(sArgs.earSide).freqData(idxF,:)));
836
                        surf(this.dirCoord,freqData_dB(idxF,:),phase,unused{:});
837
                        c = colorbar;ylabel(c,'Phase in rad')
838
                end
839
                title([sArgs.earSide ', f = ' num2str(round(this.freqVector(idxF)/100)/10) ' kHz'])
840 841
            end
            
842
            function display(this)
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
                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
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
                
            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
877 878
            end
            
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
            %% 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
922
                            usedBins = thisC.freq2index(sArgs.filter(1)):thisC.freq2index(sArgs.filter(2));
923
                            phase = unwrap(angle(thisC.freqData(3:end,:)));
924
                            freqVector = thisC.freqVector;
925
                            t0_freq = bsxfun(@rdivide, phase,2*pi*freqVector(3:end));
926
                            t0_freq = t0_freq(~isnan(t0_freq(:,1)),:);
927
                            t0_mean = mean(t0_freq(3+usedBins,:)); %mean is smoother than max; lower freq smooths also the result
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 953 954 955 956 957 958 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
                            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'));
991 992
                end
            end
993 994 995 996 997 998
            
            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');
999
                
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                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
1012
            end
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            
            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
            
1023
            this = interp(varargin);
1024 1025 1026 1027 1028
            %
            % 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
1029
            %
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
            % 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
            
            
1061 1062
            this = reduce_spatial(this,coords,varargin);
            % Function to spatially reduce the HRTF. 
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 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
            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');
                
1116 1117
            end
            
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 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
            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
                
1168
                Y               = ita_sph_base(this.dirCoord,Nmeas,'real');   % calculate real-valued SHs using the measurement grid (high SH-order)
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
                
                %% 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;
                
                
1196
                switch sArgs.type
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                    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]);
1216
                    case 'complex'
1217 1218
                        thisS = this;
                        thisS.freqData  = hrtf_smoo_wo_ITD; %rbo test
1219
                end
1220 1221 1222 1223 1224
                
                t2 = toc;
                
                fprintf(['[itaHRTF.smooth_spatial] Calculation finished after ',num2str(round(t2*100/60)/100),' min\n'])
                
1225 1226
            end
            
1227
            %% Plot
1228
            
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
            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);
1243
                phiC_deg    = sort(mod(rad2deg(thisS.phi_Unique),360));
1244 1245
                nTheta      = numel(thetaC_deg);
                nPhi        = numel(phiC_deg);
1246
                coord       = reshape(mod(thisS.dirCoord.phi_deg,360),nTheta,nPhi);
1247
                [~, idxC]   = sort(coord,2);
1248
                [~, idxCT]  = uniquetol(thisS.dirCoord.theta_deg,eps);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
                
                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');
1275
                    
1276 1277
                    [xticks, xlabels] = ita_plottools_ticks('log');
                    set(gca,'yTick',xticks,'yticklabel',xlabels)
1278
                    
1279 1280
                    cMax = max(max(ITD(2:end,:)));
                    cMin = abs(min(min(ITD(2:end,:))));
1281
                    
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
                    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',0:30:360)
                    title('ITD in Milliseconds')
                elseif strcmp(sArgs.plot_type,'line') || numel(sArgs.theta_deg)== 1
                    % angle dependent ITD (phi)
                    plot(phiC_deg,ITD_SS*1000)
                    yMax = max(abs(ITD_SS(:)));
                    ylim([-yMax yMax]*1100);
                    grid on
                    set(gca,'layer','top')
                    xlabel('Azimuth Angle in Degree');
                    ylabel('ITD in Milliseconds');
                    set(gca,'xTick',0:30:360)
1308
                    legend(ita_sprintf('%i^\circ', round(thetaC_deg)))
1309
                end
1310 1311
            end
            
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
            function plot_freqSlice(varargin)
                % init
                sArgs       = struct('pos1_data','itaHRTF', 'earSide', 'L','plane','horizontal','axes_handle',gca);
                [this,sArgs]= ita_parse_arguments(sArgs,varargin);
                ah          = sArgs.axes_handle;
                
                phiC_deg    = rad2deg(unique(round(this.phi_Unique*100)/100));
                thetaC_deg  = rad2deg(unique(round(this.theta_Unique*100)/100));
                
                % create slice
                if numel(thetaC_deg)>1 && numel( phiC_deg)>1
                    ita_verbose_info(' More than one elevation in this object!', 0);
                    if strcmp(sArgs.plane,'horizontal')
                        thetaC_deg  = 90;
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
1326
                        thisC       = this.sphericalSlice('theta_deg', thetaC_deg,1);
1327 1328
                    elseif strcmp(sArgs.plane,'median')
                        phiC_deg    = 0;
Jan-Gerrit Richter's avatar
Jan-Gerrit Richter committed
1329
                        thisC       = this.sphericalSlice('phi_deg', phiC_deg,1);
1330 1331
                    else
                       error('Unknown plane option: Either horizontal or median'); 
1332 1333 1334 1335 1336 1337 1338
                    end
                else thisC = this;
                end
                
                % multi defined coordinates
                if numel(phiC_deg)<thisC.dirCoord.nPoints && numel(thetaC_deg) ==1
                    ita_verbose_info(' Coordinates are not unique!', 0);
1339
                    [~,ia] = uniquetol(thisC.dirCoord.phi,'stable');
1340 1341 1342
                    thisC = thisC.direction(ia);
                elseif numel(thetaC_deg)<thisC.dirCoord.nPoints && numel(phiC_deg) ==1
                    ita_verbose_info(' Coordinates are not unique!', 0);
1343
                    [~,ia] = uniquetol(thisC.dirCoord.theta,'stable');
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
                    thisC = thisC.direction(ia);
                end
                
                % sort phi from lowest to highest
                if  numel( phiC_deg)>1
                    [~,idxPhiS] = sort(thisC.dirCoord.phi_deg);
                    thisCs = thisC.direction(idxPhiS);
                    yticks = round(min(rad2deg(thisCs.phi_Unique))/10)*10:30:round(max(rad2deg(thisCs.phi_Unique))/10)*10;
                else
                    [~,idxPhiS] = sort(thisC.dirCoord.theta_deg);
                    thisCs = thisC.direction(idxPhiS);
                    yticks = round(min(rad2deg(thisCs.theta_Unique))/10)*10:30: round(max(rad2deg(thisCs.theta_Unique))/10)*10;
                end
                
                % theta or phi slice
                earSidePlot = sArgs.earSide;
                if numel(phiC_deg)>1,
                    xData = phiC_deg;
1362
                    strTitle =[ earSidePlot ' ear, \theta = ' num2str(round(thetaC_deg)) '^\circ'];
1363 1364
                    strXlabel = '\phi in Degree';
                else
1365 1366
                    xData = thisC.theta_UniqueDeg;
                    strTitle =[earSidePlot ' ear, \phi = ' num2str(round(phiC_deg)) '^\circ'];
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
                    strXlabel = '\theta in Degree';
                end
                
                % Plot properties
                %             position = get(0,'ScreenSize');
                %             figure
                %             set(gcf,'Position',[10 50 position(3:4)*0.85]);
                
                idxfMax = find(this.freqVector>2e4,1,'first');
                if isempty(idxfMax), idxfMax = this.nBins; end
                fMax = thisCs.freqVector(idxfMax);
1378
%                 [tick, lab] = ita_plottools_ticks('log');
1379 1380 1381 1382 1383 1384 1385 1386 1387
                
                data_dB= thisCs.freqData_dB;
                cMax = max(max(data_dB(2:idxfMax,:)));
                cMin = min(min(data_dB(2:idxfMax,:)))*0.5;
                
                pcolor(ah, thisCs.freqVector,xData,data_dB(:,thisCs.EarSide == earSidePlot)');
                [xticks, xlabels] = ita_plottools_ticks('log');
                
                set(ah,'xTick',xticks,'xticklabel',xlabels)
1388
                set(ah,'yTick',yticks,'yticklabel',yticks)
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
                
                caxis([cMin cMax]);
                set(ah, 'XScale', 'log')
                
                title(strTitle)
                
                shading interp