% THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS 
% OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
% DISCLAIMED.  IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
% OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
% SUCH DAMAGE.

function conditionalpdf=learnpdf(pitchpriors, warppdfs)
% Learn the conditional probability distribution P(alpha|F0) from training data

% For each of N speakers:
% Pitchpriors are given as mean pitch (Hz) from pitch tracker
%   pitchpriors = Nx1 vector
% Warps are pdf P(X|a) given by SRI recognizer
%   warppdfs = NxW matrix, W is number of warp factors
pitchaxis=1:1:400;             
warpsteps=min(size(warppdfs));

% numers is the joint pdf P(pitch,warp)
% denoms is the marginal pdf P(pitch)
numers = zeros(warpsteps, length(pitchaxis)) + realmin;
denoms = zeros(warpsteps, length(pitchaxis)) + warpsteps*realmin;

for speaker = 1:length(pitchpriors),
    pitch  = pitchpriors(speaker,1);    %P(F0) = 1 at mean(F0) 
    warppdf = exp(warppdfs(speaker,:)); %Convert from log scale        
    warppdf = warppdf / sum(warppdf);   %Normalize: discrete prob sums to 1
    warppdf = transpose(warppdf);       %arbitrary orientation

    numers(:,pitch) = numers(:,pitch) + warppdf;       
    denoms(:,pitch) = denoms(:,pitch) + 1;
end

conditionalpdf = numers ./ denoms;
% Smooth along the pitch dimension with a zero-phase filter
conditionalpdf = transpose(filtfilt(0.1*ones(1,10),[1], transpose(conditionalpdf)));


    
    
