function g = statistical_inefficiency(A)
% Estimate statisical inefficiency of a timeseries.
%
% ARGUMENTS
%   A - timeseries to compute normalized fluctuation autocorrelation function for
%
% RETURNS
%   g - estimate of statistical inefficiency
%
% REFERENCES
%
% [1] Chodera JD et al. JCTC 2007

% Determine length of timeseries.
T = length(A);

% Compute sample mean.
EA = mean(A);

% Compute fluctuation timeseries.
dA = A - EA;

% Compute t = 0 term.
CAA0 = mean(dA.*dA);

% Initialize g.
g = 1.0;

% Set "safe" tau_max.
tau_max = round(T/2);

% Estimate normalized fluctuation correlation function.
for tau = 1:tau_max
  % Compute normalized fluctuation correlation function.
  CAA = mean(dA(1:T-tau) .* dA(1+tau:T)) / CAA0;

  % Stop accumulating when we hit a negative value.
  if (CAA <= 0.0)
    %break;
  end

  % Stop accumulating when we hit 3 * g.
  if (tau > 3*g)
    break;
  end
  
  % Accumulate contribution to g.
  g = g + 2 * CAA * (1.0 - tau/T);
end

% Ensure g is at least 1.0.
if (g < 1.0)
  g = 1.0;
end

return;

