%Embosi_Q
%
% Louis Goldstein
%
% 15 April 2020
%
% idea:
% 
% trigger boundary tone (BT) activation at the location where it is maximally
% activated.
% 
% Factors contributing to activation:
% Lexical tone factor (L): Trigger on syllable that is a H followed by a low.
%   Model by calculating the tone difference between the current syll and
%   the next.
% Boundary factor(B): Trigger as close to the boundary as possible.
%   Model by computing first order decay backwards from maximal value at
%   value.
% 
% Interaction:
%    We want  to trigger at a point that optimizes both clseness to
%    boundary and lexical tone. Interaction suggests product. 
%    So multiply: activation is B*L 
%  
% Inhibition:
%    Total amount of downstream activation inhibits activation 
%    This factor doesn't seem to br useful.
%
% arguments:
% input:
% s      cell array of 'H' 'L' for successive syllables
% output:
% pos       postition where H L% boundary tone is maximally activated 
% maxtot    value of maximum boundary tone activation at that position

function [pos, maxtot] = EmbosiQ (s)

close all

nsyll = length(s);
k = .25;  % stiffness of B dynamics

% Convert H, L to f0

tf = strfind(s,'H');
f0 (tf) = 200;

tf = strfind(s,'L');
f0 (tf) = 150;

% compute L: lexical contribution to BT 
for i = 1: nsyll-1 
    L(i) = f0(i) - f0(i+1);
end
L(nsyll)  = 0;

% compute B: boundary contribution to BT
B(nsyll) = 500; % initial value of B at boundary
for j = nsyll-1 : -1 : 1
    B(j) = -k*(B(j+1)) + B(j+1);  
end

BTact = B .* L;  % Interaction

% Compute Inhibition
for i = 1: nsyll-1
    in = 0;
    for j = i+1 : nsyll        
       in = in + BTact(j);
    end
    inh (i) = -in;
end
inh(nsyll) = 0;

BTtot = BTact + inh; % total activation including downstream inhibition

subplot (2,1,1)
plot (L, '-o');
hold on
plot (B, '-o');
hold off
title (s, 'Fontsize', 18)
legend ('L', 'B', 'location', 'northwest');

subplot (2,1,2)
plot (BTact, 'o-');
hold on
plot (inh, '-o');
plot (BTtot, '-o');
xlabel ('Syllable', 'Fontsize', 18)
legend ('BTact', 'inh','BTtot','location', 'northwest');
hold off

[maxtot, pos] = max (BTact);





    
