% Author: Elsa W. Birch, ewbirch@stanford.edu, Covert Lab - Stanford Bioengineering
% Date: 4/24/2011
% Version: associated with production of the figures for Birch et al. 2012 
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
%
% Summary: Set exchange flux bounds based on physical avalailibty
% 
%
% Inputs: 
%
% Outputs: 
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
%
% Notes: 
%
%
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

function fluxBoundsCurrent = FBA_EB_setCurrentExchangeFluxBounds(deltaTime, currentBiomass, ...
                                                      currentMedia,fluxBoundsDefault, ...
                                                      mediaExchangeRxnIdxList)
% This function updates the flux bounds to account for avalible media, both exhaustable
% and unlimited, while maintaing consistancy with default physical bounds (these are
% labeled default in variable names, but may be input to this function having been 
% modified from model defualts based on regulatory rules, etc)

% first caclulate the maximum allowable flux from media per biomass*time basis
%
% for i over all exchange reactions each corresponding to a single exchange metabolite ,
% also i
%
%            [ metabolite_i ]                        mmol
% flux_i > ---------------------   , with units ---------------
%           (Biomass) * delta_t                 (gram DCW) * h
%
% ( because flux_i > 0 is export by cell and 
%           flux_i < 0 is import by cell.
%
fluxBoundMetaboliteAvalible = - currentMedia / currentBiomass / deltaTime;

% Get default flux bounds for comparison to avalible media
fluxBoundsDefaultExchange = fluxBoundsDefault(mediaExchangeRxnIdxList,:);

% use whichever is more limiting, default or avalible metabolite
% ( max is more limiting based on sign convention that export is positive flux value)
fluxBoundsExchangeLower = max([fluxBoundMetaboliteAvalible,fluxBoundsDefaultExchange(:,1)],[],2);

% check that lower limit is not greater than upper bound, of so replace with zero
fluxBoundsExchangeFeasible = fluxBoundsExchangeLower < fluxBoundsDefaultExchange(:,2);
fluxBoundsExchange = [fluxBoundsExchangeLower, fluxBoundsDefaultExchange(:,2) ] ...
                        .* [fluxBoundsExchangeFeasible,fluxBoundsExchangeFeasible];

% replace default fluxes which are further constrained by avalibility
fluxBoundsCurrent = fluxBoundsDefault;
fluxBoundsCurrent(mediaExchangeRxnIdxList,:) = fluxBoundsExchange;

end % function FBA_EB_setCurrentExchangeFluxBounds

