signature:
def batch ( self , batch_size , batch_num , fluxes = True ) :
    """Create a batch generator .
 This is useful to generate n batches of m samples each .
 Parameters
 batch _ size : int
 The number of samples contained in each batch ( m ) .
 batch _ num : int
 The number of batches in the generator ( n ) .
 fluxes : boolean
 Whether to return fluxes or the internal solver variables . If set
 to False will return a variable for each forward and backward flux
 as well as all additional variables you might have defined in the
 model .
 Yields
 pandas . DataFrame
 A DataFrame with dimensions ( batch _ size x n _ r ) containing
 a valid flux sample for a total of n _ r reactions ( or variables if
 fluxes = False ) in each row ."""

implementation:
for i in range ( batch_num ) :
    yield self . sample ( batch_size , fluxes = fluxes )


signature:
def validate ( self , samples ) :
    """Validate a set of samples for equality and inequality feasibility .
 Can be used to check whether the generated samples and warmup points
 are feasible .
 Parameters
 samples : numpy . matrix
 Must be of dimension ( n _ samples x n _ reactions ) . Contains the
 samples to be validated . Samples must be from fluxes .
 Returns
 numpy . array
 A one - dimensional numpy array of length containing
 a code of 1 to 3 letters denoting the validation result :
 - ' v ' means feasible in bounds and equality constraints
 - ' l ' means a lower bound violation
 - ' u ' means a lower bound validation
 - ' e ' means and equality constraint violation"""

implementation:
samples = np . atleast_2d ( samples )
prob = self . problem
if samples . shape [ 1 ] == len ( self . model . reactions ) :
    S = create_stoichiometric_matrix ( self . model )
    b = np . array ( [ self . model . constraints [ m . id ] . lb for m in self . model . metabolites ] )
    bounds = np . array ( [ r . bounds for r in self . model . reactions ] ) . T
elif samples . shape [ 1 ] == len ( self . model . variables ) :
    S = prob . equalities
    b = prob . b
    bounds = prob . variable_bounds
else :
    raise ValueError ( "Wrong number of columns. samples must have a " "column for each flux or variable defined in the " "model!" )
feasibility = np . abs ( S . dot ( samples . T ) . T - b ) . max ( axis = 1 )
lb_error = ( samples - bounds [ 0 , ] ) . min ( axis = 1 )
ub_error = ( bounds [ 1 , ] - samples ) . min ( axis = 1 )
if ( samples . shape [ 1 ] == len ( self . model . variables ) and prob . inequalities . shape [ 0 ] ) :
    consts = prob . inequalities . dot ( samples . T )
    lb_error = np . minimum ( lb_error , ( consts - prob . bounds [ 0 , ] ) . min ( axis = 1 ) )
    ub_error = np . minimum ( ub_error , ( prob . bounds [ 1 , ] - consts ) . min ( axis = 1 ) )
valid = ( ( feasibility < self . feasibility_tol ) & ( lb_error > - self . bounds_tol ) & ( ub_error > - self . bounds_tol ) )
codes = np . repeat ( "" , valid . shape [ 0 ] ) . astype ( np . dtype ( ( str , 3 ) ) )
codes [ valid ] = "v"
codes [ lb_error <= - self . bounds_tol ] = np . char . add ( codes [ lb_error <= - self . bounds_tol ] , "l" )
codes [ ub_error <= - self . bounds_tol ] = np . char . add ( codes [ ub_error <= - self . bounds_tol ] , "u" )
codes [ feasibility > self . feasibility_tol ] = np . char . add ( codes [ feasibility > self . feasibility_tol ] , "e" )
return codes


signature:
def prune_unused_metabolites ( cobra_model ) :
    """Remove metabolites that are not involved in any reactions and
 returns pruned model
 Parameters
 cobra _ model : class : ` ~ cobra . core . Model . Model ` object
 the model to remove unused metabolites from
 Returns
 output _ model : class : ` ~ cobra . core . Model . Model ` object
 input model with unused metabolites removed
 inactive _ metabolites : list of class : ` ~ cobra . core . reaction . Reaction `
 list of metabolites that were removed"""

implementation:
output_model = cobra_model . copy ( )
inactive_metabolites = [ m for m in output_model . metabolites if len ( m . reactions ) == 0 ]
output_model . remove_metabolites ( inactive_metabolites )
return output_model , inactive_metabolites


signature:
def prune_unused_reactions ( cobra_model ) :
    """Remove reactions with no assigned metabolites , returns pruned model
 Parameters
 cobra _ model : class : ` ~ cobra . core . Model . Model ` object
 the model to remove unused reactions from
 Returns
 output _ model : class : ` ~ cobra . core . Model . Model ` object
 input model with unused reactions removed
 reactions _ to _ prune : list of class : ` ~ cobra . core . reaction . Reaction `
 list of reactions that were removed"""

implementation:
output_model = cobra_model . copy ( )
reactions_to_prune = [ r for r in output_model . reactions if len ( r . metabolites ) == 0 ]
output_model . remove_reactions ( reactions_to_prune )
return output_model , reactions_to_prune


signature:
def undelete_model_genes ( cobra_model ) :
    """Undoes the effects of a call to delete _ model _ genes in place .
 cobra _ model : A cobra . Model which will be modified in place"""

implementation:
if cobra_model . _trimmed_genes is not None :
    for x in cobra_model . _trimmed_genes :
        x . functional = True
if cobra_model . _trimmed_reactions is not None :
    for the_reaction , ( lower_bound , upper_bound ) in cobra_model . _trimmed_reactions . items ( ) :
        the_reaction . lower_bound = lower_bound
        the_reaction . upper_bound = upper_bound
cobra_model . _trimmed_genes = [ ]
cobra_model . _trimmed_reactions = { }
cobra_model . _trimmed = False


signature:
def find_gene_knockout_reactions ( cobra_model , gene_list , compiled_gene_reaction_rules = None ) :
    """identify reactions which will be disabled when the genes are knocked out
 cobra _ model : : class : ` ~ cobra . core . Model . Model `
 gene _ list : iterable of : class : ` ~ cobra . core . Gene . Gene `
 compiled _ gene _ reaction _ rules : dict of { reaction _ id : compiled _ string }
 If provided , this gives pre - compiled gene _ reaction _ rule strings .
 The compiled rule strings can be evaluated much faster . If a rule
 is not provided , the regular expression evaluation will be used .
 Because not all gene _ reaction _ rule strings can be evaluated , this
 dict must exclude any rules which can not be used with eval ."""

implementation:
potential_reactions = set ( )
for gene in gene_list :
    if isinstance ( gene , string_types ) :
        gene = cobra_model . genes . get_by_id ( gene )
    potential_reactions . update ( gene . _reaction )
gene_set = { str ( i ) for i in gene_list }
if compiled_gene_reaction_rules is None :
    compiled_gene_reaction_rules = { r : parse_gpr ( r . gene_reaction_rule ) [ 0 ] for r in potential_reactions }
return [ r for r in potential_reactions if not eval_gpr ( compiled_gene_reaction_rules [ r ] , gene_set ) ]


signature:
def delete_model_genes ( cobra_model , gene_list , cumulative_deletions = True , disable_orphans = False ) :
    """delete _ model _ genes will set the upper and lower bounds for reactions
 catalysed by the genes in gene _ list if deleting the genes means that
 the reaction cannot proceed according to
 cobra _ model . reactions [ : ] . gene _ reaction _ rule
 cumulative _ deletions : False or True . If True then any previous
 deletions will be maintained in the model ."""

implementation:
if disable_orphans :
    raise NotImplementedError ( "disable_orphans not implemented" )
if not hasattr ( cobra_model , '_trimmed' ) :
    cobra_model . _trimmed = False
    cobra_model . _trimmed_genes = [ ]
    cobra_model . _trimmed_reactions = { }
    # Store the old bounds in here .
# older models have this
if cobra_model . _trimmed_genes is None :
    cobra_model . _trimmed_genes = [ ]
if cobra_model . _trimmed_reactions is None :
    cobra_model . _trimmed_reactions = { }
# Allow a single gene to be fed in as a string instead of a list .
if not hasattr ( gene_list , '__iter__' ) or hasattr ( gene_list , 'id' ) : # cobra . Gene has _ _ iter _ _
    gene_list = [ gene_list ]
if not hasattr ( gene_list [ 0 ] , 'id' ) :
    if gene_list [ 0 ] in cobra_model . genes :
        tmp_gene_dict = dict ( [ ( x . id , x ) for x in cobra_model . genes ] )
    else : # assume we ' re dealing with names if no match to an id
        tmp_gene_dict = dict ( [ ( x . name , x ) for x in cobra_model . genes ] )
    gene_list = [ tmp_gene_dict [ x ] for x in gene_list ]
# Make the genes non - functional
for x in gene_list :
    x . functional = False
if cumulative_deletions :
    gene_list . extend ( cobra_model . _trimmed_genes )
else :
    undelete_model_genes ( cobra_model )
for the_reaction in find_gene_knockout_reactions ( cobra_model , gene_list ) : # Running this on an already deleted reaction will overwrite the
# stored reaction bounds .
    if the_reaction in cobra_model . _trimmed_reactions :
        continue
    old_lower_bound = the_reaction . lower_bound
    old_upper_bound = the_reaction . upper_bound
    cobra_model . _trimmed_reactions [ the_reaction ] = ( old_lower_bound , old_upper_bound )
    the_reaction . lower_bound = 0.
    the_reaction . upper_bound = 0.
    cobra_model . _trimmed = True
cobra_model . _trimmed_genes = list ( set ( cobra_model . _trimmed_genes + gene_list ) )


signature:
def remove_genes ( cobra_model , gene_list , remove_reactions = True ) :
    """remove genes entirely from the model
 This will also simplify all gene _ reaction _ rules with this
 gene inactivated ."""

implementation:
gene_set = { cobra_model . genes . get_by_id ( str ( i ) ) for i in gene_list }
gene_id_set = { i . id for i in gene_set }
remover = _GeneRemover ( gene_id_set )
ast_rules = get_compiled_gene_reaction_rules ( cobra_model )
target_reactions = [ ]
for reaction , rule in iteritems ( ast_rules ) :
    if reaction . gene_reaction_rule is None or len ( reaction . gene_reaction_rule ) == 0 :
        continue
    # reactions to remove
    if remove_reactions and not eval_gpr ( rule , gene_id_set ) :
        target_reactions . append ( reaction )
    else : # if the reaction is not removed , remove the gene
    # from its gpr
        remover . visit ( rule )
        new_rule = ast2str ( rule )
        if new_rule != reaction . gene_reaction_rule :
            reaction . gene_reaction_rule = new_rule
for gene in gene_set :
    cobra_model . genes . remove ( gene )
    # remove reference to the gene in all groups
    associated_groups = cobra_model . get_associated_groups ( gene )
    for group in associated_groups :
        group . remove_members ( gene )
cobra_model . remove_reactions ( target_reactions )


signature:
def gapfill ( model , universal = None , lower_bound = 0.05 , penalties = None , demand_reactions = True , exchange_reactions = False , iterations = 1 ) :
    """Perform gapfilling on a model .
 See documentation for the class GapFiller .
 Parameters
 model : cobra . Model
 The model to perform gap filling on .
 universal : cobra . Model , None
 A universal model with reactions that can be used to complete the
 model . Only gapfill considering demand and exchange reactions if
 left missing .
 lower _ bound : float
 The minimally accepted flux for the objective in the filled model .
 penalties : dict , None
 A dictionary with keys being ' universal ' ( all reactions included in
 the universal model ) , ' exchange ' and ' demand ' ( all additionally
 added exchange and demand reactions ) for the three reaction types .
 Can also have reaction identifiers for reaction specific costs .
 Defaults are 1 , 100 and 1 respectively .
 iterations : int
 The number of rounds of gapfilling to perform . For every iteration ,
 the penalty for every used reaction increases linearly . This way ,
 the algorithm is encouraged to search for alternative solutions
 which may include previously used reactions . I . e . , with enough
 iterations pathways including 10 steps will eventually be reported
 even if the shortest pathway is a single reaction .
 exchange _ reactions : bool
 Consider adding exchange ( uptake ) reactions for all metabolites
 in the model .
 demand _ reactions : bool
 Consider adding demand reactions for all metabolites .
 Returns
 iterable
 list of lists with on set of reactions that completes the model per
 requested iteration .
 Examples
 > > > import cobra . test as ct
 > > > from cobra import Model
 > > > from cobra . flux _ analysis import gapfill
 > > > model = ct . create _ test _ model ( " salmonella " )
 > > > universal = Model ( ' universal ' )
 > > > universal . add _ reactions ( model . reactions . GF6PTA . copy ( ) )
 > > > model . remove _ reactions ( [ model . reactions . GF6PTA ] )
 > > > gapfill ( model , universal )"""

implementation:
gapfiller = GapFiller ( model , universal = universal , lower_bound = lower_bound , penalties = penalties , demand_reactions = demand_reactions , exchange_reactions = exchange_reactions )
return gapfiller . fill ( iterations = iterations )


signature:
def extend_model ( self , exchange_reactions = False , demand_reactions = True ) :
    """Extend gapfilling model .
 Add reactions from universal model and optionally exchange and
 demand reactions for all metabolites in the model to perform
 gapfilling on .
 Parameters
 exchange _ reactions : bool
 Consider adding exchange ( uptake ) reactions for all metabolites
 in the model .
 demand _ reactions : bool
 Consider adding demand reactions for all metabolites ."""

implementation:
for rxn in self . universal . reactions :
    rxn . gapfilling_type = 'universal'
new_metabolites = self . universal . metabolites . query ( lambda metabolite : metabolite not in self . model . metabolites )
self . model . add_metabolites ( new_metabolites )
existing_exchanges = [ ]
for rxn in self . universal . boundary :
    existing_exchanges = existing_exchanges + [ met . id for met in list ( rxn . metabolites ) ]
for met in self . model . metabolites :
    if exchange_reactions : # check for exchange reaction in model already
        if met . id not in existing_exchanges :
            rxn = self . universal . add_boundary ( met , type = 'exchange_smiley' , lb = - 1000 , ub = 0 , reaction_id = 'EX_{}' . format ( met . id ) )
            rxn . gapfilling_type = 'exchange'
    if demand_reactions :
        rxn = self . universal . add_boundary ( met , type = 'demand_smiley' , lb = 0 , ub = 1000 , reaction_id = 'DM_{}' . format ( met . id ) )
        rxn . gapfilling_type = 'demand'
new_reactions = self . universal . reactions . query ( lambda reaction : reaction not in self . model . reactions )
self . model . add_reactions ( new_reactions )


signature:
def update_costs ( self ) :
    """Update the coefficients for the indicator variables in the objective .
 Done incrementally so that second time the function is called ,
 active indicators in the current solutions gets higher cost than the
 unused indicators ."""

implementation:
for var in self . indicators :
    if var not in self . costs :
        self . costs [ var ] = var . cost
    else :
        if var . _get_primal ( ) > self . integer_threshold :
            self . costs [ var ] += var . cost
self . model . objective . set_linear_coefficients ( self . costs )


signature:
def add_switches_and_objective ( self ) :
    """Update gapfilling model with switches and the indicator objective ."""

implementation:
constraints = list ( )
big_m = max ( max ( abs ( b ) for b in r . bounds ) for r in self . model . reactions )
prob = self . model . problem
for rxn in self . model . reactions :
    if not hasattr ( rxn , 'gapfilling_type' ) :
        continue
    indicator = prob . Variable ( name = 'indicator_{}' . format ( rxn . id ) , lb = 0 , ub = 1 , type = 'binary' )
    if rxn . id in self . penalties :
        indicator . cost = self . penalties [ rxn . id ]
    else :
        indicator . cost = self . penalties [ rxn . gapfilling_type ]
    indicator . rxn_id = rxn . id
    self . indicators . append ( indicator )
    # if z = 1 v _ i is allowed non - zero
    # v _ i - Mz < = 0 and v _ i + Mz > = 0
    constraint_lb = prob . Constraint ( rxn . flux_expression - big_m * indicator , ub = 0 , name = 'constraint_lb_{}' . format ( rxn . id ) , sloppy = True )
    constraint_ub = prob . Constraint ( rxn . flux_expression + big_m * indicator , lb = 0 , name = 'constraint_ub_{}' . format ( rxn . id ) , sloppy = True )
    constraints . extend ( [ constraint_lb , constraint_ub ] )
self . model . add_cons_vars ( self . indicators )
self . model . add_cons_vars ( constraints , sloppy = True )
self . model . objective = prob . Objective ( Zero , direction = 'min' , sloppy = True )
self . model . objective . set_linear_coefficients ( { i : 1 for i in self . indicators } )
self . update_costs ( )


signature:
def fill ( self , iterations = 1 ) :
    """Perform the gapfilling by iteratively solving the model , updating
 the costs and recording the used reactions .
 Parameters
 iterations : int
 The number of rounds of gapfilling to perform . For every
 iteration , the penalty for every used reaction increases
 linearly . This way , the algorithm is encouraged to search for
 alternative solutions which may include previously used
 reactions . I . e . , with enough iterations pathways including 10
 steps will eventually be reported even if the shortest pathway
 is a single reaction .
 Returns
 iterable
 A list of lists where each element is a list reactions that were
 used to gapfill the model .
 Raises
 RuntimeError
 If the model fails to be validated ( i . e . the original model with
 the proposed reactions added , still cannot get the required flux
 through the objective ) ."""

implementation:
used_reactions = list ( )
for i in range ( iterations ) :
    self . model . slim_optimize ( error_value = None , message = 'gapfilling optimization failed' )
    solution = [ self . model . reactions . get_by_id ( ind . rxn_id ) for ind in self . indicators if ind . _get_primal ( ) > self . integer_threshold ]
    if not self . validate ( solution ) :
        raise RuntimeError ( 'failed to validate gapfilled model, ' 'try lowering the integer_threshold' )
    used_reactions . append ( solution )
    self . update_costs ( )
return used_reactions


signature:
def find_external_compartment ( model ) :
    """Find the external compartment in the model .
 Uses a simple heuristic where the external compartment should be the one
 with the most exchange reactions .
 Arguments
 model : cobra . Model
 A cobra model .
 Returns
 str
 The putative external compartment ."""

implementation:
if model . boundary :
    counts = pd . Series ( tuple ( r . compartments ) [ 0 ] for r in model . boundary )
    most = counts . value_counts ( )
    most = most . index [ most == most . max ( ) ] . to_series ( )
else :
    most = None
like_external = compartment_shortlist [ "e" ] + [ "e" ]
matches = pd . Series ( [ co in like_external for co in model . compartments ] , index = model . compartments )
if matches . sum ( ) == 1 :
    compartment = matches . index [ matches ] [ 0 ]
    LOGGER . info ( "Compartment `%s` sounds like an external compartment. " "Using this one without counting boundary reactions" % compartment )
    return compartment
elif most is not None and matches . sum ( ) > 1 and matches [ most ] . sum ( ) == 1 :
    compartment = most [ matches [ most ] ] [ 0 ]
    LOGGER . warning ( "There are several compartments that look like an " "external compartment but `%s` has the most boundary " "reactions, so using that as the external " "compartment." % compartment )
    return compartment
elif matches . sum ( ) > 1 :
    raise RuntimeError ( "There are several compartments (%s) that look " "like external compartments but we can't tell " "which one to use. Consider renaming your " "compartments please." )
if most is not None :
    return most [ 0 ]
    LOGGER . warning ( "Could not identify an external compartment by name and" " choosing one with the most boundary reactions. That " "might be complete nonsense or change suddenly. " "Consider renaming your compartments using " "`Model.compartments` to fix this." )
# No info in the model , so give up
raise RuntimeError ( "The heuristic for discovering an external compartment " "relies on names and boundary reactions. Yet, there " "are neither compartments with recognized names nor " "boundary reactions in the model." )


signature:
def is_boundary_type ( reaction , boundary_type , external_compartment ) :
    """Check whether a reaction is an exchange reaction .
 Arguments
 reaction : cobra . Reaction
 The reaction to check .
 boundary _ type : str
 What boundary type to check for . Must be one of
 " exchange " , " demand " , or " sink " .
 external _ compartment : str
 The id for the external compartment .
 Returns
 boolean
 Whether the reaction looks like the requested type . Might be based
 on a heuristic ."""

implementation:
# Check if the reaction has an annotation . Annotations dominate everything .
sbo_term = reaction . annotation . get ( "sbo" , "" )
if isinstance ( sbo_term , list ) :
    sbo_term = sbo_term [ 0 ]
sbo_term = sbo_term . upper ( )
if sbo_term == sbo_terms [ boundary_type ] :
    return True
if sbo_term in [ sbo_terms [ k ] for k in sbo_terms if k != boundary_type ] :
    return False
# Check if the reaction is in the correct compartment ( exterior or inside )
correct_compartment = external_compartment in reaction . compartments
if boundary_type != "exchange" :
    correct_compartment = not correct_compartment
# Check if the reaction has the correct reversibility
rev_type = True
if boundary_type == "demand" :
    rev_type = not reaction . reversibility
elif boundary_type == "sink" :
    rev_type = reaction . reversibility
return ( reaction . boundary and not any ( ex in reaction . id for ex in excludes [ boundary_type ] ) and correct_compartment and rev_type )


signature:
def find_boundary_types ( model , boundary_type , external_compartment = None ) :
    """Find specific boundary reactions .
 Arguments
 model : cobra . Model
 A cobra model .
 boundary _ type : str
 What boundary type to check for . Must be one of
 " exchange " , " demand " , or " sink " .
 external _ compartment : str or None
 The id for the external compartment . If None it will be detected
 automatically .
 Returns
 list of cobra . reaction
 A list of likely boundary reactions of a user defined type ."""

implementation:
if not model . boundary :
    LOGGER . warning ( "There are no boundary reactions in this model. " "Therefore specific types of boundary reactions such " "as 'exchanges', 'demands' or 'sinks' cannot be " "identified." )
    return [ ]
if external_compartment is None :
    external_compartment = find_external_compartment ( model )
return model . reactions . query ( lambda r : is_boundary_type ( r , boundary_type , external_compartment ) )


signature:
def normalize_cutoff ( model , zero_cutoff = None ) :
    """Return a valid zero cutoff value ."""

implementation:
if zero_cutoff is None :
    return model . tolerance
else :
    if zero_cutoff < model . tolerance :
        raise ValueError ( "The chosen zero cutoff cannot be less than the model's " "tolerance value." )
    else :
        return zero_cutoff


signature:
def _sample_chain ( args ) :
    """Sample a single chain for OptGPSampler .
 center and n _ samples are updated locally and forgotten afterwards ."""

implementation:
n , idx = args
# has to be this way to work in Python 2.7
center = sampler . center
np . random . seed ( ( sampler . _seed + idx ) % np . iinfo ( np . int32 ) . max )
pi = np . random . randint ( sampler . n_warmup )
prev = sampler . warmup [ pi , ]
prev = step ( sampler , center , prev - center , 0.95 )
n_samples = max ( sampler . n_samples , 1 )
samples = np . zeros ( ( n , center . shape [ 0 ] ) )
for i in range ( 1 , sampler . thinning * n + 1 ) :
    pi = np . random . randint ( sampler . n_warmup )
    delta = sampler . warmup [ pi , ] - center
    prev = step ( sampler , prev , delta )
    if sampler . problem . homogeneous and ( n_samples * sampler . thinning % sampler . nproj == 0 ) :
        prev = sampler . _reproject ( prev )
        center = sampler . _reproject ( center )
    if i % sampler . thinning == 0 :
        samples [ i // sampler . thinning - 1 , ] = prev
    center = ( ( n_samples * center ) / ( n_samples + 1 ) + prev / ( n_samples + 1 ) )
    n_samples += 1
return ( sampler . retries , samples )


signature:
def sample ( self , n , fluxes = True ) :
    """Generate a set of samples .
 This is the basic sampling function for all hit - and - run samplers .
 Paramters
 n : int
 The minimum number of samples that are generated at once
 ( see Notes ) .
 fluxes : boolean
 Whether to return fluxes or the internal solver variables . If set
 to False will return a variable for each forward and backward flux
 as well as all additional variables you might have defined in the
 model .
 Returns
 numpy . matrix
 Returns a matrix with ` n ` rows , each containing a flux sample .
 Notes
 Performance of this function linearly depends on the number
 of reactions in your model and the thinning factor .
 If the number of processes is larger than one , computation is split
 across as the CPUs of your machine . This may shorten computation time .
 However , there is also overhead in setting up parallel computation so
 we recommend to calculate large numbers of samples at once
 ( ` n ` > 1000 ) ."""

implementation:
if self . processes > 1 :
    n_process = np . ceil ( n / self . processes ) . astype ( int )
    n = n_process * self . processes
    # The cast to list is weird but not doing it gives recursion
    # limit errors , something weird going on with multiprocessing
    args = list ( zip ( [ n_process ] * self . processes , range ( self . processes ) ) )
    # No with statement or starmap here since Python 2 . x
    # does not support it : (
    mp = Pool ( self . processes , initializer = mp_init , initargs = ( self , ) )
    results = mp . map ( _sample_chain , args , chunksize = 1 )
    mp . close ( )
    mp . join ( )
    chains = np . vstack ( [ r [ 1 ] for r in results ] )
    self . retries += sum ( r [ 0 ] for r in results )
else :
    mp_init ( self )
    results = _sample_chain ( ( n , 0 ) )
    chains = results [ 1 ]
# Update the global center
self . center = ( self . n_samples * self . center + np . atleast_2d ( chains ) . sum ( 0 ) ) / ( self . n_samples + n )
self . n_samples += n
if fluxes :
    names = [ r . id for r in self . model . reactions ]
    return pandas . DataFrame ( chains [ : , self . fwd_idx ] - chains [ : , self . rev_idx ] , columns = names )
else :
    names = [ v . name for v in self . model . variables ]
    return pandas . DataFrame ( chains , columns = names )


signature:
def ast2str ( expr , level = 0 , names = None ) :
    """convert compiled ast to gene _ reaction _ rule str
 Parameters
 expr : str
 string for a gene reaction rule , e . g " a and b "
 level : int
 internal use only
 names : dict
 Dict where each element id a gene identifier and the value is the
 gene name . Use this to get a rule str which uses names instead . This
 should be done for display purposes only . All gene _ reaction _ rule
 strings which are computed with should use the id .
 Returns
 string
 The gene reaction rule"""

implementation:
if isinstance ( expr , Expression ) :
    return ast2str ( expr . body , 0 , names ) if hasattr ( expr , "body" ) else ""
elif isinstance ( expr , Name ) :
    return names . get ( expr . id , expr . id ) if names else expr . id
elif isinstance ( expr , BoolOp ) :
    op = expr . op
    if isinstance ( op , Or ) :
        str_exp = " or " . join ( ast2str ( i , level + 1 , names ) for i in expr . values )
    elif isinstance ( op , And ) :
        str_exp = " and " . join ( ast2str ( i , level + 1 , names ) for i in expr . values )
    else :
        raise TypeError ( "unsupported operation " + op . __class__ . __name )
    return "(" + str_exp + ")" if level else str_exp
elif expr is None :
    return ""
else :
    raise TypeError ( "unsupported operation  " + repr ( expr ) )


signature:
def eval_gpr ( expr , knockouts ) :
    """evaluate compiled ast of gene _ reaction _ rule with knockouts
 Parameters
 expr : Expression
 The ast of the gene reaction rule
 knockouts : DictList , set
 Set of genes that are knocked out
 Returns
 bool
 True if the gene reaction rule is true with the given knockouts
 otherwise false"""

implementation:
if isinstance ( expr , Expression ) :
    return eval_gpr ( expr . body , knockouts )
elif isinstance ( expr , Name ) :
    return expr . id not in knockouts
elif isinstance ( expr , BoolOp ) :
    op = expr . op
    if isinstance ( op , Or ) :
        return any ( eval_gpr ( i , knockouts ) for i in expr . values )
    elif isinstance ( op , And ) :
        return all ( eval_gpr ( i , knockouts ) for i in expr . values )
    else :
        raise TypeError ( "unsupported operation " + op . __class__ . __name__ )
elif expr is None :
    return True
else :
    raise TypeError ( "unsupported operation  " + repr ( expr ) )


signature:
def parse_gpr ( str_expr ) :
    """parse gpr into AST
 Parameters
 str _ expr : string
 string with the gene reaction rule to parse
 Returns
 tuple
 elements ast _ tree and gene _ ids as a set"""

implementation:
str_expr = str_expr . strip ( )
if len ( str_expr ) == 0 :
    return None , set ( )
for char , escaped in replacements :
    if char in str_expr :
        str_expr = str_expr . replace ( char , escaped )
escaped_str = keyword_re . sub ( "__cobra_escape__" , str_expr )
escaped_str = number_start_re . sub ( "__cobra_escape__" , escaped_str )
tree = ast_parse ( escaped_str , "<string>" , "eval" )
cleaner = GPRCleaner ( )
cleaner . visit ( tree )
eval_gpr ( tree , set ( ) )
# ensure the rule can be evaluated
return tree , cleaner . gene_set


signature:
def knock_out ( self ) :
    """Knockout gene by marking it as non - functional and setting all
 associated reactions bounds to zero .
 The change is reverted upon exit if executed within the model as
 context ."""

implementation:
self . functional = False
for reaction in self . reactions :
    if not reaction . functional :
        reaction . bounds = ( 0 , 0 )


signature:
def remove_from_model ( self , model = None , make_dependent_reactions_nonfunctional = True ) :
    """Removes the association
 Parameters
 model : cobra model
 The model to remove the gene from
 make _ dependent _ reactions _ nonfunctional : bool
 If True then replace the gene with ' False ' in the gene
 association , else replace the gene with ' True '
 . . deprecated : : 0.4
 Use cobra . manipulation . delete _ model _ genes to simulate knockouts
 and cobra . manipulation . remove _ genes to remove genes from
 the model ."""

implementation:
warn ( "Use cobra.manipulation.remove_genes instead" )
if model is not None :
    if model != self . _model :
        raise Exception ( "%s is a member of %s, not %s" % ( repr ( self ) , repr ( self . _model ) , repr ( model ) ) )
if self . _model is None :
    raise Exception ( '%s is not in a model' % repr ( self ) )
if make_dependent_reactions_nonfunctional :
    gene_state = 'False'
else :
    gene_state = 'True'
the_gene_re = re . compile ( '(^|(?<=( |\()))%s(?=( |\)|$))' % re . escape ( self . id ) )
# remove reference to the gene in all groups
associated_groups = self . _model . get_associated_groups ( self )
for group in associated_groups :
    group . remove_members ( self )
self . _model . genes . remove ( self )
self . _model = None
for the_reaction in list ( self . _reaction ) :
    the_reaction . _gene_reaction_rule = the_gene_re . sub ( gene_state , the_reaction . gene_reaction_rule )
    the_reaction . _genes . remove ( self )
    # Now , deactivate the reaction if its gene association evaluates
    # to False
    the_gene_reaction_relation = the_reaction . gene_reaction_rule
    for other_gene in the_reaction . _genes :
        other_gene_re = re . compile ( '(^|(?<=( |\()))%s(?=( |\)|$))' % re . escape ( other_gene . id ) )
        the_gene_reaction_relation = other_gene_re . sub ( 'True' , the_gene_reaction_relation )
    if not eval ( the_gene_reaction_relation ) :
        the_reaction . lower_bound = 0
        the_reaction . upper_bound = 0
self . _reaction . clear ( )


signature:
def moma ( model , solution = None , linear = True ) :
    """Compute a single solution based on ( linear ) MOMA .
 Compute a new flux distribution that is at a minimal distance to a
 previous reference solution . Minimization of metabolic adjustment ( MOMA ) is
 generally used to assess the impact
 of knock - outs . Thus the typical usage is to provide a wildtype flux
 distribution as reference and a model in knock - out state .
 Parameters
 model : cobra . Model
 The model state to compute a MOMA - based solution for .
 solution : cobra . Solution , optional
 A ( wildtype ) reference solution .
 linear : bool , optional
 Whether to use the linear MOMA formulation or not ( default True ) .
 Returns
 cobra . Solution
 A flux distribution that is at a minimal distance compared to the
 reference solution .
 See Also
 add _ moma : add MOMA constraints and objective"""

implementation:
with model :
    add_moma ( model = model , solution = solution , linear = linear )
    solution = model . optimize ( )
return solution


signature:
def add_moma ( model , solution = None , linear = True ) :
    r"""Add constraints and objective representing for MOMA .
 This adds variables and constraints for the minimization of metabolic
 adjustment ( MOMA ) to the model .
 Parameters
 model : cobra . Model
 The model to add MOMA constraints and objective to .
 solution : cobra . Solution , optional
 A previous solution to use as a reference . If no solution is given ,
 one will be computed using pFBA .
 linear : bool , optional
 Whether to use the linear MOMA formulation or not ( default True ) .
 Notes
 In the original MOMA [ 1 ] _ specification one looks for the flux distribution
 of the deletion ( v ^ d ) closest to the fluxes without the deletion ( v ) .
 In math this means :
 minimize \ sum _ i ( v ^ d _ i - v _ i ) ^ 2
 s . t . Sv ^ d = 0
 lb _ i < = v ^ d _ i < = ub _ i
 Here , we use a variable transformation v ^ t : = v ^ d _ i - v _ i . Substituting
 and using the fact that Sv = 0 gives :
 minimize \ sum _ i ( v ^ t _ i ) ^ 2
 s . t . Sv ^ d = 0
 v ^ t = v ^ d _ i - v _ i
 lb _ i < = v ^ d _ i < = ub _ i
 So basically we just re - center the flux space at the old solution and then
 find the flux distribution closest to the new zero ( center ) . This is the
 same strategy as used in cameo .
 In the case of linear MOMA [ 2 ] _ , we instead minimize \ sum _ i abs ( v ^ t _ i ) . The
 linear MOMA is typically significantly faster . Also quadratic MOMA tends
 to give flux distributions in which all fluxes deviate from the reference
 fluxes a little bit whereas linear MOMA tends to give flux distributions
 where the majority of fluxes are the same reference with few fluxes
 deviating a lot ( typical effect of L2 norm vs L1 norm ) .
 The former objective function is saved in the optlang solver interface as
 ` ` " moma _ old _ objective " ` ` and this can be used to immediately extract the
 value of the former objective after MOMA optimization .
 See Also
 pfba : parsimonious FBA
 References
 . . [ 1 ] Segrè , Daniel , Dennis Vitkup , and George M . Church . “ Analysis of
 Optimality in Natural and Perturbed Metabolic Networks . ”
 Proceedings of the National Academy of Sciences 99 , no . 23
 ( November 12 , 2002 ) : 15112 . https : / / doi . org / 10.1073 / pnas . 232349399.
 . . [ 2 ] Becker , Scott A , Adam M Feist , Monica L Mo , Gregory Hannum ,
 Bernhard Ø Palsson , and Markus J Herrgard . “ Quantitative
 Prediction of Cellular Metabolism with Constraint - Based Models :
 The COBRA Toolbox . ” Nature Protocols 2 ( March 29 , 2007 ) : 727."""

implementation:
if 'moma_old_objective' in model . solver . variables :
    raise ValueError ( 'model is already adjusted for MOMA' )
# Fall back to default QP solver if current one has no QP capability
if not linear :
    model . solver = sutil . choose_solver ( model , qp = True )
if solution is None :
    solution = pfba ( model )
prob = model . problem
v = prob . Variable ( "moma_old_objective" )
c = prob . Constraint ( model . solver . objective . expression - v , lb = 0.0 , ub = 0.0 , name = "moma_old_objective_constraint" )
to_add = [ v , c ]
model . objective = prob . Objective ( Zero , direction = "min" , sloppy = True )
obj_vars = [ ]
for r in model . reactions :
    flux = solution . fluxes [ r . id ]
    if linear :
        components = sutil . add_absolute_expression ( model , r . flux_expression , name = "moma_dist_" + r . id , difference = flux , add = False )
        to_add . extend ( components )
        obj_vars . append ( components . variable )
    else :
        dist = prob . Variable ( "moma_dist_" + r . id )
        const = prob . Constraint ( r . flux_expression - dist , lb = flux , ub = flux , name = "moma_constraint_" + r . id )
        to_add . extend ( [ dist , const ] )
        obj_vars . append ( dist ** 2 )
model . add_cons_vars ( to_add )
if linear :
    model . objective . set_linear_coefficients ( { v : 1.0 for v in obj_vars } )
else :
    model . objective = prob . Objective ( add ( obj_vars ) , direction = "min" , sloppy = True )


signature:
def _fix_type ( value ) :
    """convert possible types to str , float , and bool"""

implementation:
# Because numpy floats can not be pickled to json
if isinstance ( value , string_types ) :
    return str ( value )
if isinstance ( value , float_ ) :
    return float ( value )
if isinstance ( value , bool_ ) :
    return bool ( value )
if isinstance ( value , set ) :
    return list ( value )
if isinstance ( value , dict ) :
    return OrderedDict ( ( key , value [ key ] ) for key in sorted ( value ) )
# handle legacy Formula type
if value . __class__ . __name__ == "Formula" :
    return str ( value )
if value is None :
    return ""
return value


signature:
def _update_optional ( cobra_object , new_dict , optional_attribute_dict , ordered_keys ) :
    """update new _ dict with optional attributes from cobra _ object"""

implementation:
for key in ordered_keys :
    default = optional_attribute_dict [ key ]
    value = getattr ( cobra_object , key )
    if value is None or value == default :
        continue
    new_dict [ key ] = _fix_type ( value )


signature:
def model_to_dict ( model , sort = False ) :
    """Convert model to a dict .
 Parameters
 model : cobra . Model
 The model to reformulate as a dict .
 sort : bool , optional
 Whether to sort the metabolites , reactions , and genes or maintain the
 order defined in the model .
 Returns
 OrderedDict
 A dictionary with elements , ' genes ' , ' compartments ' , ' id ' ,
 ' metabolites ' , ' notes ' and ' reactions ' ; where ' metabolites ' , ' genes '
 and ' metabolites ' are in turn lists with dictionaries holding all
 attributes to form the corresponding object .
 See Also
 cobra . io . model _ from _ dict"""

implementation:
obj = OrderedDict ( )
obj [ "metabolites" ] = list ( map ( metabolite_to_dict , model . metabolites ) )
obj [ "reactions" ] = list ( map ( reaction_to_dict , model . reactions ) )
obj [ "genes" ] = list ( map ( gene_to_dict , model . genes ) )
obj [ "id" ] = model . id
_update_optional ( model , obj , _OPTIONAL_MODEL_ATTRIBUTES , _ORDERED_OPTIONAL_MODEL_KEYS )
if sort :
    get_id = itemgetter ( "id" )
    obj [ "metabolites" ] . sort ( key = get_id )
    obj [ "reactions" ] . sort ( key = get_id )
    obj [ "genes" ] . sort ( key = get_id )
return obj


signature:
def model_from_dict ( obj ) :
    """Build a model from a dict .
 Models stored in json are first formulated as a dict that can be read to
 cobra model using this function .
 Parameters
 obj : dict
 A dictionary with elements , ' genes ' , ' compartments ' , ' id ' ,
 ' metabolites ' , ' notes ' and ' reactions ' ; where ' metabolites ' , ' genes '
 and ' metabolites ' are in turn lists with dictionaries holding all
 attributes to form the corresponding object .
 Returns
 cora . core . Model
 The generated model .
 See Also
 cobra . io . model _ to _ dict"""

implementation:
if 'reactions' not in obj :
    raise ValueError ( 'Object has no reactions attribute. Cannot load.' )
model = Model ( )
model . add_metabolites ( [ metabolite_from_dict ( metabolite ) for metabolite in obj [ 'metabolites' ] ] )
model . genes . extend ( [ gene_from_dict ( gene ) for gene in obj [ 'genes' ] ] )
model . add_reactions ( [ reaction_from_dict ( reaction , model ) for reaction in obj [ 'reactions' ] ] )
objective_reactions = [ rxn for rxn in obj [ 'reactions' ] if rxn . get ( 'objective_coefficient' , 0 ) != 0 ]
coefficients = { model . reactions . get_by_id ( rxn [ 'id' ] ) : rxn [ 'objective_coefficient' ] for rxn in objective_reactions }
set_objective ( model , coefficients )
for k , v in iteritems ( obj ) :
    if k in { 'id' , 'name' , 'notes' , 'compartments' , 'annotation' } :
        setattr ( model , k , v )
return model


signature:
def _get_id_compartment ( id ) :
    """extract the compartment from the id string"""

implementation:
bracket_search = _bracket_re . findall ( id )
if len ( bracket_search ) == 1 :
    return bracket_search [ 0 ] [ 1 ]
underscore_search = _underscore_re . findall ( id )
if len ( underscore_search ) == 1 :
    return underscore_search [ 0 ] [ 1 ]
return None


signature:
def _cell ( x ) :
    """translate an array x into a MATLAB cell array"""

implementation:
x_no_none = [ i if i is not None else "" for i in x ]
return array ( x_no_none , dtype = np_object )


signature:
def load_matlab_model ( infile_path , variable_name = None , inf = inf ) :
    """Load a cobra model stored as a . mat file
 Parameters
 infile _ path : str
 path to the file to to read
 variable _ name : str , optional
 The variable name of the model in the . mat file . If this is not
 specified , then the first MATLAB variable which looks like a COBRA
 model will be used
 inf : value
 The value to use for infinite bounds . Some solvers do not handle
 infinite values so for using those , set this to a high numeric value .
 Returns
 cobra . core . Model . Model :
 The resulting cobra model"""

implementation:
if not scipy_io :
    raise ImportError ( 'load_matlab_model requires scipy' )
data = scipy_io . loadmat ( infile_path )
possible_names = [ ]
if variable_name is None : # skip meta variables
    meta_vars = { "__globals__" , "__header__" , "__version__" }
    possible_names = sorted ( i for i in data if i not in meta_vars )
    if len ( possible_names ) == 1 :
        variable_name = possible_names [ 0 ]
if variable_name is not None :
    return from_mat_struct ( data [ variable_name ] , model_id = variable_name , inf = inf )
for possible_name in possible_names :
    try :
        return from_mat_struct ( data [ possible_name ] , model_id = possible_name , inf = inf )
    except ValueError :
        pass
# If code here is executed , then no model was found .
raise IOError ( "no COBRA model found" )


signature:
def save_matlab_model ( model , file_name , varname = None ) :
    """Save the cobra model as a . mat file .
 This . mat file can be used directly in the MATLAB version of COBRA .
 Parameters
 model : cobra . core . Model . Model object
 The model to save
 file _ name : str or file - like object
 The file to save to
 varname : string
 The name of the variable within the workspace"""

implementation:
if not scipy_io :
    raise ImportError ( 'load_matlab_model requires scipy' )
if varname is None :
    varname = str ( model . id ) if model . id is not None and len ( model . id ) > 0 else "exported_model"
mat = create_mat_dict ( model )
scipy_io . savemat ( file_name , { varname : mat } , appendmat = True , oned_as = "column" )


signature:
def create_mat_dict ( model ) :
    """create a dict mapping model attributes to arrays"""

implementation:
rxns = model . reactions
mets = model . metabolites
mat = OrderedDict ( )
mat [ "mets" ] = _cell ( [ met_id for met_id in create_mat_metabolite_id ( model ) ] )
mat [ "metNames" ] = _cell ( mets . list_attr ( "name" ) )
mat [ "metFormulas" ] = _cell ( [ str ( m . formula ) for m in mets ] )
try :
    mat [ "metCharge" ] = array ( mets . list_attr ( "charge" ) ) * 1.
except TypeError : # can ' t have any None entries for charge , or this will fail
    pass
mat [ "genes" ] = _cell ( model . genes . list_attr ( "id" ) )
# make a matrix for rxnGeneMat
# reactions are rows , genes are columns
rxn_gene = scipy_sparse . dok_matrix ( ( len ( model . reactions ) , len ( model . genes ) ) )
if min ( rxn_gene . shape ) > 0 :
    for i , reaction in enumerate ( model . reactions ) :
        for gene in reaction . genes :
            rxn_gene [ i , model . genes . index ( gene ) ] = 1
    mat [ "rxnGeneMat" ] = rxn_gene
mat [ "grRules" ] = _cell ( rxns . list_attr ( "gene_reaction_rule" ) )
mat [ "rxns" ] = _cell ( rxns . list_attr ( "id" ) )
mat [ "rxnNames" ] = _cell ( rxns . list_attr ( "name" ) )
mat [ "subSystems" ] = _cell ( rxns . list_attr ( "subsystem" ) )
stoich_mat = create_stoichiometric_matrix ( model )
mat [ "S" ] = stoich_mat if stoich_mat is not None else [ [ ] ]
# multiply by 1 to convert to float , working around scipy bug
# https : / / github . com / scipy / scipy / issues / 4537
mat [ "lb" ] = array ( rxns . list_attr ( "lower_bound" ) ) * 1.
mat [ "ub" ] = array ( rxns . list_attr ( "upper_bound" ) ) * 1.
mat [ "b" ] = array ( mets . list_attr ( "_bound" ) ) * 1.
mat [ "c" ] = array ( rxns . list_attr ( "objective_coefficient" ) ) * 1.
mat [ "rev" ] = array ( rxns . list_attr ( "reversibility" ) ) * 1
mat [ "description" ] = str ( model . id )
return mat


signature:
def from_mat_struct ( mat_struct , model_id = None , inf = inf ) :
    """create a model from the COBRA toolbox struct
 The struct will be a dict read in by scipy . io . loadmat"""

implementation:
m = mat_struct
if m . dtype . names is None :
    raise ValueError ( "not a valid mat struct" )
if not { "rxns" , "mets" , "S" , "lb" , "ub" } <= set ( m . dtype . names ) :
    raise ValueError ( "not a valid mat struct" )
if "c" in m . dtype . names :
    c_vec = m [ "c" ] [ 0 , 0 ]
else :
    c_vec = None
    warn ( "objective vector 'c' not found" )
model = Model ( )
if model_id is not None :
    model . id = model_id
elif "description" in m . dtype . names :
    description = m [ "description" ] [ 0 , 0 ] [ 0 ]
    if not isinstance ( description , string_types ) and len ( description ) > 1 :
        model . id = description [ 0 ]
        warn ( "Several IDs detected, only using the first." )
    else :
        model . id = description
else :
    model . id = "imported_model"
for i , name in enumerate ( m [ "mets" ] [ 0 , 0 ] ) :
    new_metabolite = Metabolite ( )
    new_metabolite . id = str ( name [ 0 ] [ 0 ] )
    if all ( var in m . dtype . names for var in [ 'metComps' , 'comps' , 'compNames' ] ) :
        comp_index = m [ "metComps" ] [ 0 , 0 ] [ i ] [ 0 ] - 1
        new_metabolite . compartment = m [ 'comps' ] [ 0 , 0 ] [ comp_index ] [ 0 ] [ 0 ]
        if new_metabolite . compartment not in model . compartments :
            comp_name = m [ 'compNames' ] [ 0 , 0 ] [ comp_index ] [ 0 ] [ 0 ]
            model . compartments [ new_metabolite . compartment ] = comp_name
    else :
        new_metabolite . compartment = _get_id_compartment ( new_metabolite . id )
        if new_metabolite . compartment not in model . compartments :
            model . compartments [ new_metabolite . compartment ] = new_metabolite . compartment
    try :
        new_metabolite . name = str ( m [ "metNames" ] [ 0 , 0 ] [ i ] [ 0 ] [ 0 ] )
    except ( IndexError , ValueError ) :
        pass
    try :
        new_metabolite . formula = str ( m [ "metFormulas" ] [ 0 ] [ 0 ] [ i ] [ 0 ] [ 0 ] )
    except ( IndexError , ValueError ) :
        pass
    try :
        new_metabolite . charge = float ( m [ "metCharge" ] [ 0 , 0 ] [ i ] [ 0 ] )
        int_charge = int ( new_metabolite . charge )
        if new_metabolite . charge == int_charge :
            new_metabolite . charge = int_charge
    except ( IndexError , ValueError ) :
        pass
    model . add_metabolites ( [ new_metabolite ] )
new_reactions = [ ]
coefficients = { }
for i , name in enumerate ( m [ "rxns" ] [ 0 , 0 ] ) :
    new_reaction = Reaction ( )
    new_reaction . id = str ( name [ 0 ] [ 0 ] )
    new_reaction . lower_bound = float ( m [ "lb" ] [ 0 , 0 ] [ i ] [ 0 ] )
    new_reaction . upper_bound = float ( m [ "ub" ] [ 0 , 0 ] [ i ] [ 0 ] )
    if isinf ( new_reaction . lower_bound ) and new_reaction . lower_bound < 0 :
        new_reaction . lower_bound = - inf
    if isinf ( new_reaction . upper_bound ) and new_reaction . upper_bound > 0 :
        new_reaction . upper_bound = inf
    if c_vec is not None :
        coefficients [ new_reaction ] = float ( c_vec [ i ] [ 0 ] )
    try :
        new_reaction . gene_reaction_rule = str ( m [ 'grRules' ] [ 0 , 0 ] [ i ] [ 0 ] [ 0 ] )
    except ( IndexError , ValueError ) :
        pass
    try :
        new_reaction . name = str ( m [ "rxnNames" ] [ 0 , 0 ] [ i ] [ 0 ] [ 0 ] )
    except ( IndexError , ValueError ) :
        pass
    try :
        new_reaction . subsystem = str ( m [ 'subSystems' ] [ 0 , 0 ] [ i ] [ 0 ] [ 0 ] )
    except ( IndexError , ValueError ) :
        pass
    new_reactions . append ( new_reaction )
model . add_reactions ( new_reactions )
set_objective ( model , coefficients )
coo = scipy_sparse . coo_matrix ( m [ "S" ] [ 0 , 0 ] )
for i , j , v in zip ( coo . row , coo . col , coo . data ) :
    model . reactions [ j ] . add_metabolites ( { model . metabolites [ i ] : v } )
return model


signature:
def model_to_pymatbridge ( model , variable_name = "model" , matlab = None ) :
    """send the model to a MATLAB workspace through pymatbridge
 This model can then be manipulated through the COBRA toolbox
 Parameters
 variable _ name : str
 The variable name to which the model will be assigned in the
 MATLAB workspace
 matlab : None or pymatbridge . Matlab instance
 The MATLAB workspace to which the variable will be sent . If
 this is None , then this will be sent to the same environment
 used in IPython magics ."""

implementation:
if scipy_sparse is None :
    raise ImportError ( "`model_to_pymatbridge` requires scipy!" )
if matlab is None : # assumed to be running an IPython magic
    from IPython import get_ipython
    matlab = get_ipython ( ) . magics_manager . registry [ "MatlabMagics" ] . Matlab
model_info = create_mat_dict ( model )
S = model_info [ "S" ] . todok ( )
model_info [ "S" ] = 0
temp_S_name = "cobra_pymatbridge_temp_" + uuid4 ( ) . hex
_check ( matlab . set_variable ( variable_name , model_info ) )
_check ( matlab . set_variable ( temp_S_name , S ) )
_check ( matlab . run_code ( "%s.S = %s;" % ( variable_name , temp_S_name ) ) )
# all vectors need to be transposed
for i in model_info . keys ( ) :
    if i == "S" :
        continue
    _check ( matlab . run_code ( "{0}.{1} = {0}.{1}';" . format ( variable_name , i ) ) )
_check ( matlab . run_code ( "clear %s;" % temp_S_name ) )


signature:
def get_context ( obj ) :
    """Search for a context manager"""

implementation:
try :
    return obj . _contexts [ - 1 ]
except ( AttributeError , IndexError ) :
    pass
try :
    return obj . _model . _contexts [ - 1 ]
except ( AttributeError , IndexError ) :
    pass
return None


signature:
def resettable ( f ) :
    """A decorator to simplify the context management of simple object
 attributes . Gets the value of the attribute prior to setting it , and stores
 a function to set the value to the old value in the HistoryManager ."""

implementation:
def wrapper ( self , new_value ) :
    context = get_context ( self )
    if context :
        old_value = getattr ( self , f . __name__ )
        # Don ' t clutter the context with unchanged variables
        if old_value == new_value :
            return
        context ( partial ( f , self , old_value ) )
    f ( self , new_value )
return wrapper


signature:
def get_solution ( model , reactions = None , metabolites = None , raise_error = False ) :
    """Generate a solution representation of the current solver state .
 Parameters
 model : cobra . Model
 The model whose reactions to retrieve values for .
 reactions : list , optional
 An iterable of ` cobra . Reaction ` objects . Uses ` model . reactions ` by
 default .
 metabolites : list , optional
 An iterable of ` cobra . Metabolite ` objects . Uses ` model . metabolites ` by
 default .
 raise _ error : bool
 If true , raise an OptimizationError if solver status is not optimal .
 Returns
 cobra . Solution
 Note
 This is only intended for the ` optlang ` solver interfaces and not the
 legacy solvers ."""

implementation:
check_solver_status ( model . solver . status , raise_error = raise_error )
if reactions is None :
    reactions = model . reactions
if metabolites is None :
    metabolites = model . metabolites
rxn_index = list ( )
fluxes = empty ( len ( reactions ) )
reduced = empty ( len ( reactions ) )
var_primals = model . solver . primal_values
shadow = empty ( len ( metabolites ) )
if model . solver . is_integer :
    reduced . fill ( nan )
    shadow . fill ( nan )
    for ( i , rxn ) in enumerate ( reactions ) :
        rxn_index . append ( rxn . id )
        fluxes [ i ] = var_primals [ rxn . id ] - var_primals [ rxn . reverse_id ]
    met_index = [ met . id for met in metabolites ]
else :
    var_duals = model . solver . reduced_costs
    for ( i , rxn ) in enumerate ( reactions ) :
        forward = rxn . id
        reverse = rxn . reverse_id
        rxn_index . append ( forward )
        fluxes [ i ] = var_primals [ forward ] - var_primals [ reverse ]
        reduced [ i ] = var_duals [ forward ] - var_duals [ reverse ]
    met_index = list ( )
    constr_duals = model . solver . shadow_prices
    for ( i , met ) in enumerate ( metabolites ) :
        met_index . append ( met . id )
        shadow [ i ] = constr_duals [ met . id ]
return Solution ( model . solver . objective . value , model . solver . status , Series ( index = rxn_index , data = fluxes , name = "fluxes" ) , Series ( index = rxn_index , data = reduced , name = "reduced_costs" ) , Series ( index = met_index , data = shadow , name = "shadow_prices" ) )


signature:
def get_metabolite_compartments ( self ) :
    """Return all metabolites ' compartments ."""

implementation:
warn ( 'use Model.compartments instead' , DeprecationWarning )
return { met . compartment for met in self . metabolites if met . compartment is not None }


signature:
def medium ( self , medium ) :
    """Get or set the constraints on the model exchanges .
 ` model . medium ` returns a dictionary of the bounds for each of the
 boundary reactions , in the form of ` { rxn _ id : bound } ` , where ` bound `
 specifies the absolute value of the bound in direction of metabolite
 creation ( i . e . , lower _ bound for ` met < - - ` , upper _ bound for ` met - - > ` )
 Parameters
 medium : dictionary - like
 The medium to initialize . medium should be a dictionary defining
 ` { rxn _ id : bound } ` pairs ."""

implementation:
def set_active_bound ( reaction , bound ) :
    if reaction . reactants :
        reaction . lower_bound = - bound
    elif reaction . products :
        reaction . upper_bound = bound
# Set the given media bounds
media_rxns = list ( )
exchange_rxns = frozenset ( self . exchanges )
for rxn_id , bound in iteritems ( medium ) :
    rxn = self . reactions . get_by_id ( rxn_id )
    if rxn not in exchange_rxns :
        LOGGER . warn ( "%s does not seem to be an" " an exchange reaction. Applying bounds anyway." , rxn . id )
    media_rxns . append ( rxn )
    set_active_bound ( rxn , bound )
media_rxns = frozenset ( media_rxns )
# Turn off reactions not present in media
for rxn in ( exchange_rxns - media_rxns ) :
    set_active_bound ( rxn , 0 )


signature:
def copy ( self ) :
    """Provides a partial ' deepcopy ' of the Model . All of the Metabolite ,
 Gene , and Reaction objects are created anew but in a faster fashion
 than deepcopy"""

implementation:
new = self . __class__ ( )
do_not_copy_by_ref = { "metabolites" , "reactions" , "genes" , "notes" , "annotation" , "groups" }
for attr in self . __dict__ :
    if attr not in do_not_copy_by_ref :
        new . __dict__ [ attr ] = self . __dict__ [ attr ]
new . notes = deepcopy ( self . notes )
new . annotation = deepcopy ( self . annotation )
new . metabolites = DictList ( )
do_not_copy_by_ref = { "_reaction" , "_model" }
for metabolite in self . metabolites :
    new_met = metabolite . __class__ ( )
    for attr , value in iteritems ( metabolite . __dict__ ) :
        if attr not in do_not_copy_by_ref :
            new_met . __dict__ [ attr ] = copy ( value ) if attr == "formula" else value
    new_met . _model = new
    new . metabolites . append ( new_met )
new . genes = DictList ( )
for gene in self . genes :
    new_gene = gene . __class__ ( None )
    for attr , value in iteritems ( gene . __dict__ ) :
        if attr not in do_not_copy_by_ref :
            new_gene . __dict__ [ attr ] = copy ( value ) if attr == "formula" else value
    new_gene . _model = new
    new . genes . append ( new_gene )
new . reactions = DictList ( )
do_not_copy_by_ref = { "_model" , "_metabolites" , "_genes" }
for reaction in self . reactions :
    new_reaction = reaction . __class__ ( )
    for attr , value in iteritems ( reaction . __dict__ ) :
        if attr not in do_not_copy_by_ref :
            new_reaction . __dict__ [ attr ] = copy ( value )
    new_reaction . _model = new
    new . reactions . append ( new_reaction )
    # update awareness
    for metabolite , stoic in iteritems ( reaction . _metabolites ) :
        new_met = new . metabolites . get_by_id ( metabolite . id )
        new_reaction . _metabolites [ new_met ] = stoic
        new_met . _reaction . add ( new_reaction )
    for gene in reaction . _genes :
        new_gene = new . genes . get_by_id ( gene . id )
        new_reaction . _genes . add ( new_gene )
        new_gene . _reaction . add ( new_reaction )
new . groups = DictList ( )
do_not_copy_by_ref = { "_model" , "_members" }
# Groups can be members of other groups . We initialize them first and
# then update their members .
for group in self . groups :
    new_group = group . __class__ ( group . id )
    for attr , value in iteritems ( group . __dict__ ) :
        if attr not in do_not_copy_by_ref :
            new_group . __dict__ [ attr ] = copy ( value )
    new_group . _model = new
    new . groups . append ( new_group )
for group in self . groups :
    new_group = new . groups . get_by_id ( group . id )
    # update awareness , as in the reaction copies
    new_objects = [ ]
    for member in group . members :
        if isinstance ( member , Metabolite ) :
            new_object = new . metabolites . get_by_id ( member . id )
        elif isinstance ( member , Reaction ) :
            new_object = new . reactions . get_by_id ( member . id )
        elif isinstance ( member , Gene ) :
            new_object = new . genes . get_by_id ( member . id )
        elif isinstance ( member , Group ) :
            new_object = new . genes . get_by_id ( member . id )
        else :
            raise TypeError ( "The group member {!r} is unexpectedly not a " "metabolite, reaction, gene, nor another " "group." . format ( member ) )
        new_objects . append ( new_object )
    new_group . add_members ( new_objects )
try :
    new . _solver = deepcopy ( self . solver )
    # Cplex has an issue with deep copies
except Exception : # pragma : no cover
    new . _solver = copy ( self . solver )
# pragma : no cover
# it doesn ' t make sense to retain the context of a copied model so
# assign a new empty context
new . _contexts = list ( )
return new


signature:
def add_metabolites ( self , metabolite_list ) :
    """Will add a list of metabolites to the model object and add new
 constraints accordingly .
 The change is reverted upon exit when using the model as a context .
 Parameters
 metabolite _ list : A list of ` cobra . core . Metabolite ` objects"""

implementation:
if not hasattr ( metabolite_list , '__iter__' ) :
    metabolite_list = [ metabolite_list ]
if len ( metabolite_list ) == 0 :
    return None
# First check whether the metabolites exist in the model
metabolite_list = [ x for x in metabolite_list if x . id not in self . metabolites ]
bad_ids = [ m for m in metabolite_list if not isinstance ( m . id , string_types ) or len ( m . id ) < 1 ]
if len ( bad_ids ) != 0 :
    raise ValueError ( 'invalid identifiers in {}' . format ( repr ( bad_ids ) ) )
for x in metabolite_list :
    x . _model = self
self . metabolites += metabolite_list
# from cameo . . .
to_add = [ ]
for met in metabolite_list :
    if met . id not in self . constraints :
        constraint = self . problem . Constraint ( Zero , name = met . id , lb = 0 , ub = 0 )
        to_add += [ constraint ]
self . add_cons_vars ( to_add )
context = get_context ( self )
if context :
    context ( partial ( self . metabolites . __isub__ , metabolite_list ) )
    for x in metabolite_list : # Do we care ?
        context ( partial ( setattr , x , '_model' , None ) )


signature:
def remove_metabolites ( self , metabolite_list , destructive = False ) :
    """Remove a list of metabolites from the the object .
 The change is reverted upon exit when using the model as a context .
 Parameters
 metabolite _ list : list
 A list with ` cobra . Metabolite ` objects as elements .
 destructive : bool
 If False then the metabolite is removed from all
 associated reactions . If True then all associated
 reactions are removed from the Model ."""

implementation:
if not hasattr ( metabolite_list , '__iter__' ) :
    metabolite_list = [ metabolite_list ]
# Make sure metabolites exist in model
metabolite_list = [ x for x in metabolite_list if x . id in self . metabolites ]
for x in metabolite_list :
    x . _model = None
    # remove reference to the metabolite in all groups
    associated_groups = self . get_associated_groups ( x )
    for group in associated_groups :
        group . remove_members ( x )
    if not destructive :
        for the_reaction in list ( x . _reaction ) :
            the_coefficient = the_reaction . _metabolites [ x ]
            the_reaction . subtract_metabolites ( { x : the_coefficient } )
    else :
        for x in list ( x . _reaction ) :
            x . remove_from_model ( )
self . metabolites -= metabolite_list
to_remove = [ self . solver . constraints [ m . id ] for m in metabolite_list ]
self . remove_cons_vars ( to_remove )
context = get_context ( self )
if context :
    context ( partial ( self . metabolites . __iadd__ , metabolite_list ) )
    for x in metabolite_list :
        context ( partial ( setattr , x , '_model' , self ) )


signature:
def add_boundary ( self , metabolite , type = "exchange" , reaction_id = None , lb = None , ub = None , sbo_term = None ) :
    """Add a boundary reaction for a given metabolite .
 There are three different types of pre - defined boundary reactions :
 exchange , demand , and sink reactions .
 An exchange reaction is a reversible , unbalanced reaction that adds
 to or removes an extracellular metabolite from the extracellular
 compartment .
 A demand reaction is an irreversible reaction that consumes an
 intracellular metabolite .
 A sink is similar to an exchange but specifically for intracellular
 metabolites .
 If you set the reaction ` type ` to something else , you must specify the
 desired identifier of the created reaction along with its upper and
 lower bound . The name will be given by the metabolite name and the
 given ` type ` .
 Parameters
 metabolite : cobra . Metabolite
 Any given metabolite . The compartment is not checked but you are
 encouraged to stick to the definition of exchanges and sinks .
 type : str , { " exchange " , " demand " , " sink " }
 Using one of the pre - defined reaction types is easiest . If you
 want to create your own kind of boundary reaction choose
 any other string , e . g . , ' my - boundary ' .
 reaction _ id : str , optional
 The ID of the resulting reaction . This takes precedence over the
 auto - generated identifiers but beware that it might make boundary
 reactions harder to identify afterwards when using ` model . boundary `
 or specifically ` model . exchanges ` etc .
 lb : float , optional
 The lower bound of the resulting reaction .
 ub : float , optional
 The upper bound of the resulting reaction .
 sbo _ term : str , optional
 A correct SBO term is set for the available types . If a custom
 type is chosen , a suitable SBO term should also be set .
 Returns
 cobra . Reaction
 The created boundary reaction .
 Examples
 > > > import cobra . test
 > > > model = cobra . test . create _ test _ model ( " textbook " )
 > > > demand = model . add _ boundary ( model . metabolites . atp _ c , type = " demand " )
 > > > demand . id
 ' DM _ atp _ c '
 > > > demand . name
 ' ATP demand '
 > > > demand . bounds
 (0 , 1000.0)
 > > > demand . build _ reaction _ string ( )
 ' atp _ c - - > '"""

implementation:
ub = CONFIGURATION . upper_bound if ub is None else ub
lb = CONFIGURATION . lower_bound if lb is None else lb
types = { "exchange" : ( "EX" , lb , ub , sbo_terms [ "exchange" ] ) , "demand" : ( "DM" , 0 , ub , sbo_terms [ "demand" ] ) , "sink" : ( "SK" , lb , ub , sbo_terms [ "sink" ] ) }
if type == "exchange" :
    external = find_external_compartment ( self )
    if metabolite . compartment != external :
        raise ValueError ( "The metabolite is not an external metabolite" " (compartment is `%s` but should be `%s`). " "Did you mean to add a demand or sink? " "If not, either change its compartment or " "rename the model compartments to fix this." % ( metabolite . compartment , external ) )
if type in types :
    prefix , lb , ub , default_term = types [ type ]
    if reaction_id is None :
        reaction_id = "{}_{}" . format ( prefix , metabolite . id )
    if sbo_term is None :
        sbo_term = default_term
if reaction_id is None :
    raise ValueError ( "Custom types of boundary reactions require a custom " "identifier. Please set the `reaction_id`." )
if reaction_id in self . reactions :
    raise ValueError ( "Boundary reaction '{}' already exists." . format ( reaction_id ) )
name = "{} {}" . format ( metabolite . name , type )
rxn = Reaction ( id = reaction_id , name = name , lower_bound = lb , upper_bound = ub )
rxn . add_metabolites ( { metabolite : - 1 } )
if sbo_term :
    rxn . annotation [ "sbo" ] = sbo_term
self . add_reactions ( [ rxn ] )
return rxn


signature:
def add_reactions ( self , reaction_list ) :
    """Add reactions to the model .
 Reactions with identifiers identical to a reaction already in the
 model are ignored .
 The change is reverted upon exit when using the model as a context .
 Parameters
 reaction _ list : list
 A list of ` cobra . Reaction ` objects"""

implementation:
def existing_filter ( rxn ) :
    if rxn . id in self . reactions :
        LOGGER . warning ( "Ignoring reaction '%s' since it already exists." , rxn . id )
        return False
    return True
# First check whether the reactions exist in the model .
pruned = DictList ( filter ( existing_filter , reaction_list ) )
context = get_context ( self )
# Add reactions . Also take care of genes and metabolites in the loop .
for reaction in pruned :
    reaction . _model = self
    # Build a ` list ( ) ` because the dict will be modified in the loop .
    for metabolite in list ( reaction . metabolites ) : # TODO : Should we add a copy of the metabolite instead ?
        if metabolite not in self . metabolites :
            self . add_metabolites ( metabolite )
        # A copy of the metabolite exists in the model , the reaction
        # needs to point to the metabolite in the model .
        else : # FIXME : Modifying ' private ' attributes is horrible .
            stoichiometry = reaction . _metabolites . pop ( metabolite )
            model_metabolite = self . metabolites . get_by_id ( metabolite . id )
            reaction . _metabolites [ model_metabolite ] = stoichiometry
            model_metabolite . _reaction . add ( reaction )
            if context :
                context ( partial ( model_metabolite . _reaction . remove , reaction ) )
    for gene in list ( reaction . _genes ) : # If the gene is not in the model , add it
        if not self . genes . has_id ( gene . id ) :
            self . genes += [ gene ]
            gene . _model = self
            if context : # Remove the gene later
                context ( partial ( self . genes . __isub__ , [ gene ] ) )
                context ( partial ( setattr , gene , '_model' , None ) )
        # Otherwise , make the gene point to the one in the model
        else :
            model_gene = self . genes . get_by_id ( gene . id )
            if model_gene is not gene :
                reaction . _dissociate_gene ( gene )
                reaction . _associate_gene ( model_gene )
self . reactions += pruned
if context :
    context ( partial ( self . reactions . __isub__ , pruned ) )
# from cameo . . .
self . _populate_solver ( pruned )


signature:
def remove_reactions ( self , reactions , remove_orphans = False ) :
    """Remove reactions from the model .
 The change is reverted upon exit when using the model as a context .
 Parameters
 reactions : list
 A list with reactions ( ` cobra . Reaction ` ) , or their id ' s , to remove
 remove _ orphans : bool
 Remove orphaned genes and metabolites from the model as well"""

implementation:
if isinstance ( reactions , string_types ) or hasattr ( reactions , "id" ) :
    warn ( "need to pass in a list" )
    reactions = [ reactions ]
context = get_context ( self )
for reaction in reactions : # Make sure the reaction is in the model
    try :
        reaction = self . reactions [ self . reactions . index ( reaction ) ]
    except ValueError :
        warn ( '%s not in %s' % ( reaction , self ) )
    else :
        forward = reaction . forward_variable
        reverse = reaction . reverse_variable
        if context :
            obj_coef = reaction . objective_coefficient
            if obj_coef != 0 :
                context ( partial ( self . solver . objective . set_linear_coefficients , { forward : obj_coef , reverse : - obj_coef } ) )
            context ( partial ( self . _populate_solver , [ reaction ] ) )
            context ( partial ( setattr , reaction , '_model' , self ) )
            context ( partial ( self . reactions . add , reaction ) )
        self . remove_cons_vars ( [ forward , reverse ] )
        self . reactions . remove ( reaction )
        reaction . _model = None
        for met in reaction . _metabolites :
            if reaction in met . _reaction :
                met . _reaction . remove ( reaction )
                if context :
                    context ( partial ( met . _reaction . add , reaction ) )
                if remove_orphans and len ( met . _reaction ) == 0 :
                    self . remove_metabolites ( met )
        for gene in reaction . _genes :
            if reaction in gene . _reaction :
                gene . _reaction . remove ( reaction )
                if context :
                    context ( partial ( gene . _reaction . add , reaction ) )
                if remove_orphans and len ( gene . _reaction ) == 0 :
                    self . genes . remove ( gene )
                    if context :
                        context ( partial ( self . genes . add , gene ) )
        # remove reference to the reaction in all groups
        associated_groups = self . get_associated_groups ( reaction )
        for group in associated_groups :
            group . remove_members ( reaction )


signature:
def add_groups ( self , group_list ) :
    """Add groups to the model .
 Groups with identifiers identical to a group already in the model are
 ignored .
 If any group contains members that are not in the model , these members
 are added to the model as well . Only metabolites , reactions , and genes
 can have groups .
 Parameters
 group _ list : list
 A list of ` cobra . Group ` objects to add to the model ."""

implementation:
def existing_filter ( group ) :
    if group . id in self . groups :
        LOGGER . warning ( "Ignoring group '%s' since it already exists." , group . id )
        return False
    return True
if isinstance ( group_list , string_types ) or hasattr ( group_list , "id" ) :
    warn ( "need to pass in a list" )
    group_list = [ group_list ]
pruned = DictList ( filter ( existing_filter , group_list ) )
for group in pruned :
    group . _model = self
    for member in group . members : # If the member is not associated with the model , add it
        if isinstance ( member , Metabolite ) :
            if member not in self . metabolites :
                self . add_metabolites ( [ member ] )
        if isinstance ( member , Reaction ) :
            if member not in self . reactions :
                self . add_reactions ( [ member ] )
        # TODO ( midnighter ) : ` add _ genes ` method does not exist .
        # if isinstance ( member , Gene ) :
        # if member not in self . genes :
        # self . add _ genes ( [ member ] )
    self . groups += [ group ]


signature:
def remove_groups ( self , group_list ) :
    """Remove groups from the model .
 Members of each group are not removed
 from the model ( i . e . metabolites , reactions , and genes in the group
 stay in the model after any groups containing them are removed ) .
 Parameters
 group _ list : list
 A list of ` cobra . Group ` objects to remove from the model ."""

implementation:
if isinstance ( group_list , string_types ) or hasattr ( group_list , "id" ) :
    warn ( "need to pass in a list" )
    group_list = [ group_list ]
for group in group_list : # make sure the group is in the model
    if group . id not in self . groups :
        LOGGER . warning ( "%r not in %r. Ignored." , group , self )
    else :
        self . groups . remove ( group )
        group . _model = None


signature:
def get_associated_groups ( self , element ) :
    """Returns a list of groups that an element ( reaction , metabolite , gene )
 is associated with .
 Parameters
 element : ` cobra . Reaction ` , ` cobra . Metabolite ` , or ` cobra . Gene `
 Returns
 list of ` cobra . Group `
 All groups that the provided object is a member of"""

implementation:
# check whether the element is associated with the model
return [ g for g in self . groups if element in g . members ]


signature:
def _populate_solver ( self , reaction_list , metabolite_list = None ) :
    """Populate attached solver with constraints and variables that
 model the provided reactions ."""

implementation:
constraint_terms = AutoVivification ( )
to_add = [ ]
if metabolite_list is not None :
    for met in metabolite_list :
        to_add += [ self . problem . Constraint ( Zero , name = met . id , lb = 0 , ub = 0 ) ]
self . add_cons_vars ( to_add )
for reaction in reaction_list :
    if reaction . id not in self . variables :
        forward_variable = self . problem . Variable ( reaction . id )
        reverse_variable = self . problem . Variable ( reaction . reverse_id )
        self . add_cons_vars ( [ forward_variable , reverse_variable ] )
    else :
        reaction = self . reactions . get_by_id ( reaction . id )
        forward_variable = reaction . forward_variable
        reverse_variable = reaction . reverse_variable
    for metabolite , coeff in six . iteritems ( reaction . metabolites ) :
        if metabolite . id in self . constraints :
            constraint = self . constraints [ metabolite . id ]
        else :
            constraint = self . problem . Constraint ( Zero , name = metabolite . id , lb = 0 , ub = 0 )
            self . add_cons_vars ( constraint , sloppy = True )
        constraint_terms [ constraint ] [ forward_variable ] = coeff
        constraint_terms [ constraint ] [ reverse_variable ] = - coeff
self . solver . update ( )
for reaction in reaction_list :
    reaction = self . reactions . get_by_id ( reaction . id )
    reaction . update_variable_bounds ( )
for constraint , terms in six . iteritems ( constraint_terms ) :
    constraint . set_linear_coefficients ( terms )


signature:
def slim_optimize ( self , error_value = float ( 'nan' ) , message = None ) :
    """Optimize model without creating a solution object .
 Creating a full solution object implies fetching shadow prices and
 flux values for all reactions and metabolites from the solver
 object . This necessarily takes some time and in cases where only one
 or two values are of interest , it is recommended to instead use this
 function which does not create a solution object returning only the
 value of the objective . Note however that the ` optimize ( ) ` function
 uses efficient means to fetch values so if you need fluxes / shadow
 prices for more than say 4 reactions / metabolites , then the total
 speed increase of ` slim _ optimize ` versus ` optimize ` is expected to
 be small or even negative depending on how you fetch the values
 after optimization .
 Parameters
 error _ value : float , None
 The value to return if optimization failed due to e . g .
 infeasibility . If None , raise ` OptimizationError ` if the
 optimization fails .
 message : string
 Error message to use if the model optimization did not succeed .
 Returns
 float
 The objective value ."""

implementation:
self . solver . optimize ( )
if self . solver . status == optlang . interface . OPTIMAL :
    return self . solver . objective . value
elif error_value is not None :
    return error_value
else :
    assert_optimal ( self , message )


signature:
def optimize ( self , objective_sense = None , raise_error = False ) :
    """Optimize the model using flux balance analysis .
 Parameters
 objective _ sense : { None , ' maximize ' ' minimize ' } , optional
 Whether fluxes should be maximized or minimized . In case of None ,
 the previous direction is used .
 raise _ error : bool
 If true , raise an OptimizationError if solver status is not
 optimal .
 Notes
 Only the most commonly used parameters are presented here . Additional
 parameters for cobra . solvers may be available and specified with the
 appropriate keyword argument ."""

implementation:
original_direction = self . objective . direction
self . objective . direction = { "maximize" : "max" , "minimize" : "min" } . get ( objective_sense , original_direction )
self . slim_optimize ( )
solution = get_solution ( self , raise_error = raise_error )
self . objective . direction = original_direction
return solution


signature:
def repair ( self , rebuild_index = True , rebuild_relationships = True ) :
    """Update all indexes and pointers in a model
 Parameters
 rebuild _ index : bool
 rebuild the indices kept in reactions , metabolites and genes
 rebuild _ relationships : bool
 reset all associations between genes , metabolites , model and
 then re - add them ."""

implementation:
if rebuild_index : # DictList indexes
    self . reactions . _generate_index ( )
    self . metabolites . _generate_index ( )
    self . genes . _generate_index ( )
    self . groups . _generate_index ( )
if rebuild_relationships :
    for met in self . metabolites :
        met . _reaction . clear ( )
    for gene in self . genes :
        gene . _reaction . clear ( )
    for rxn in self . reactions :
        for met in rxn . _metabolites :
            met . _reaction . add ( rxn )
        for gene in rxn . _genes :
            gene . _reaction . add ( rxn )
# point _ model to self
for l in ( self . reactions , self . genes , self . metabolites , self . groups ) :
    for e in l :
        e . _model = self


signature:
def summary ( self , solution = None , threshold = 1E-06 , fva = None , names = False , floatfmt = '.3g' ) :
    """Print a summary of the input and output fluxes of the model .
 Parameters
 solution : cobra . Solution , optional
 A previously solved model solution to use for generating the
 summary . If none provided ( default ) , the summary method will
 resolve the model . Note that the solution object must match the
 model , i . e . , changes to the model such as changed bounds ,
 added or removed reactions are not taken into account by this
 method .
 threshold : float , optional
 Threshold below which fluxes are not reported .
 fva : pandas . DataFrame , float or None , optional
 Whether or not to include flux variability analysis in the output .
 If given , fva should either be a previous FVA solution matching
 the model or a float between 0 and 1 representing the
 fraction of the optimum objective to be searched .
 names : bool , optional
 Emit reaction and metabolite names rather than identifiers ( default
 False ) .
 floatfmt : string , optional
 Format string for floats ( default ' . 3g ' ) ."""

implementation:
from cobra . flux_analysis . summary import model_summary
return model_summary ( self , solution = solution , threshold = threshold , fva = fva , names = names , floatfmt = floatfmt )


signature:
def merge ( self , right , prefix_existing = None , inplace = True , objective = 'left' ) :
    """Merge two models to create a model with the reactions from both
 models .
 Custom constraints and variables from right models are also copied
 to left model , however note that , constraints and variables are
 assumed to be the same if they have the same name .
 right : cobra . Model
 The model to add reactions from
 prefix _ existing : string
 Prefix the reaction identifier in the right that already exist
 in the left model with this string .
 inplace : bool
 Add reactions from right directly to left model object .
 Otherwise , create a new model leaving the left model untouched .
 When done within the model as context , changes to the models are
 reverted upon exit .
 objective : string
 One of ' left ' , ' right ' or ' sum ' for setting the objective of the
 resulting model to that of the corresponding model or the sum of
 both ."""

implementation:
if inplace :
    new_model = self
else :
    new_model = self . copy ( )
    new_model . id = '{}_{}' . format ( self . id , right . id )
new_reactions = deepcopy ( right . reactions )
if prefix_existing is not None :
    existing = new_reactions . query ( lambda rxn : rxn . id in self . reactions )
    for reaction in existing :
        reaction . id = '{}{}' . format ( prefix_existing , reaction . id )
new_model . add_reactions ( new_reactions )
interface = new_model . problem
new_vars = [ interface . Variable . clone ( v ) for v in right . variables if v . name not in new_model . variables ]
new_model . add_cons_vars ( new_vars )
new_cons = [ interface . Constraint . clone ( c , model = new_model . solver ) for c in right . constraints if c . name not in new_model . constraints ]
new_model . add_cons_vars ( new_cons , sloppy = True )
new_model . objective = dict ( left = self . objective , right = right . objective , sum = self . objective . expression + right . objective . expression ) [ objective ]
return new_model


signature:
def _escape_str_id ( id_str ) :
    """make a single string id SBML compliant"""

implementation:
for c in ( "'" , '"' ) :
    if id_str . startswith ( c ) and id_str . endswith ( c ) and id_str . count ( c ) == 2 :
        id_str = id_str . strip ( c )
for char , escaped_char in _renames :
    id_str = id_str . replace ( char , escaped_char )
return id_str


signature:
def escape_ID ( cobra_model ) :
    """makes all ids SBML compliant"""

implementation:
for x in chain ( [ cobra_model ] , cobra_model . metabolites , cobra_model . reactions , cobra_model . genes ) :
    x . id = _escape_str_id ( x . id )
cobra_model . repair ( )
gene_renamer = _GeneEscaper ( )
for rxn , rule in iteritems ( get_compiled_gene_reaction_rules ( cobra_model ) ) :
    if rule is not None :
        rxn . _gene_reaction_rule = ast2str ( gene_renamer . visit ( rule ) )


signature:
def rename_genes ( cobra_model , rename_dict ) :
    """renames genes in a model from the rename _ dict"""

implementation:
recompute_reactions = set ( )
# need to recomptue related genes
remove_genes = [ ]
for old_name , new_name in iteritems ( rename_dict ) : # undefined if there a value matches a different key
# because dict is unordered
    try :
        gene_index = cobra_model . genes . index ( old_name )
    except ValueError :
        gene_index = None
    old_gene_present = gene_index is not None
    new_gene_present = new_name in cobra_model . genes
    if old_gene_present and new_gene_present :
        old_gene = cobra_model . genes . get_by_id ( old_name )
        # Added in case not renaming some genes :
        if old_gene is not cobra_model . genes . get_by_id ( new_name ) :
            remove_genes . append ( old_gene )
            recompute_reactions . update ( old_gene . _reaction )
    elif old_gene_present and not new_gene_present : # rename old gene to new gene
        gene = cobra_model . genes [ gene_index ]
        # trick DictList into updating index
        cobra_model . genes . _dict . pop ( gene . id )
        # ugh
        gene . id = new_name
        cobra_model . genes [ gene_index ] = gene
    elif not old_gene_present and new_gene_present :
        pass
    else : # if not old gene _ present and not new _ gene _ present
    # the new gene ' s _ model will be set by repair
    # This would add genes from rename _ dict
    # that are not associated with a rxn
    # cobra _ model . genes . append ( Gene ( new _ name ) )
        pass
cobra_model . repair ( )
class Renamer ( NodeTransformer ) :
    def visit_Name ( self , node ) :
        node . id = rename_dict . get ( node . id , node . id )
        return node
gene_renamer = Renamer ( )
for rxn , rule in iteritems ( get_compiled_gene_reaction_rules ( cobra_model ) ) :
    if rule is not None :
        rxn . _gene_reaction_rule = ast2str ( gene_renamer . visit ( rule ) )
for rxn in recompute_reactions :
    rxn . gene_reaction_rule = rxn . _gene_reaction_rule
for i in remove_genes :
    cobra_model . genes . remove ( i )


signature:
def to_json ( model , sort = False , ** kwargs ) :
    """Return the model as a JSON document .
 ` ` kwargs ` ` are passed on to ` ` json . dumps ` ` .
 Parameters
 model : cobra . Model
 The cobra model to represent .
 sort : bool , optional
 Whether to sort the metabolites , reactions , and genes or maintain the
 order defined in the model .
 Returns
 str
 String representation of the cobra model as a JSON document .
 See Also
 save _ json _ model : Write directly to a file .
 json . dumps : Base function ."""

implementation:
obj = model_to_dict ( model , sort = sort )
obj [ u"version" ] = JSON_SPEC
return json . dumps ( obj , allow_nan = False , ** kwargs )


signature:
def save_json_model ( model , filename , sort = False , pretty = False , ** kwargs ) :
    """Write the cobra model to a file in JSON format .
 ` ` kwargs ` ` are passed on to ` ` json . dump ` ` .
 Parameters
 model : cobra . Model
 The cobra model to represent .
 filename : str or file - like
 File path or descriptor that the JSON representation should be
 written to .
 sort : bool , optional
 Whether to sort the metabolites , reactions , and genes or maintain the
 order defined in the model .
 pretty : bool , optional
 Whether to format the JSON more compactly ( default ) or in a more
 verbose but easier to read fashion . Can be partially overwritten by the
 ` ` kwargs ` ` .
 See Also
 to _ json : Return a string representation .
 json . dump : Base function ."""

implementation:
obj = model_to_dict ( model , sort = sort )
obj [ u"version" ] = JSON_SPEC
if pretty :
    dump_opts = { "indent" : 4 , "separators" : ( "," , ": " ) , "sort_keys" : True , "allow_nan" : False }
else :
    dump_opts = { "indent" : 0 , "separators" : ( "," , ":" ) , "sort_keys" : False , "allow_nan" : False }
dump_opts . update ( ** kwargs )
if isinstance ( filename , string_types ) :
    with open ( filename , "w" ) as file_handle :
        json . dump ( obj , file_handle , ** dump_opts )
else :
    json . dump ( obj , filename , ** dump_opts )


signature:
def load_json_model ( filename ) :
    """Load a cobra model from a file in JSON format .
 Parameters
 filename : str or file - like
 File path or descriptor that contains the JSON document describing the
 cobra model .
 Returns
 cobra . Model
 The cobra model as represented in the JSON document .
 See Also
 from _ json : Load from a string ."""

implementation:
if isinstance ( filename , string_types ) :
    with open ( filename , "r" ) as file_handle :
        return model_from_dict ( json . load ( file_handle ) )
else :
    return model_from_dict ( json . load ( filename ) )


signature:
def add_linear_obj ( model ) :
    """Add a linear version of a minimal medium to the model solver .
 Changes the optimization objective to finding the growth medium requiring
 the smallest total import flux : :
 minimize sum | r _ i | for r _ i in import _ reactions
 Arguments
 model : cobra . Model
 The model to modify ."""

implementation:
coefs = { }
for rxn in find_boundary_types ( model , "exchange" ) :
    export = len ( rxn . reactants ) == 1
    if export :
        coefs [ rxn . reverse_variable ] = 1
    else :
        coefs [ rxn . forward_variable ] = 1
model . objective . set_linear_coefficients ( coefs )
model . objective . direction = "min"


signature:
def add_mip_obj ( model ) :
    """Add a mixed - integer version of a minimal medium to the model .
 Changes the optimization objective to finding the medium with the least
 components : :
 minimize size ( R ) where R part of import _ reactions
 Arguments
 model : cobra . model
 The model to modify ."""

implementation:
if len ( model . variables ) > 1e4 :
    LOGGER . warning ( "the MIP version of minimal media is extremely slow for" " models that large :(" )
exchange_rxns = find_boundary_types ( model , "exchange" )
big_m = max ( abs ( b ) for r in exchange_rxns for b in r . bounds )
prob = model . problem
coefs = { }
to_add = [ ]
for rxn in exchange_rxns :
    export = len ( rxn . reactants ) == 1
    indicator = prob . Variable ( "ind_" + rxn . id , lb = 0 , ub = 1 , type = "binary" )
    if export :
        vrv = rxn . reverse_variable
        indicator_const = prob . Constraint ( vrv - indicator * big_m , ub = 0 , name = "ind_constraint_" + rxn . id )
    else :
        vfw = rxn . forward_variable
        indicator_const = prob . Constraint ( vfw - indicator * big_m , ub = 0 , name = "ind_constraint_" + rxn . id )
    to_add . extend ( [ indicator , indicator_const ] )
    coefs [ indicator ] = 1
model . add_cons_vars ( to_add )
model . solver . update ( )
model . objective . set_linear_coefficients ( coefs )
model . objective . direction = "min"


signature:
def _as_medium ( exchanges , tolerance = 1e-6 , exports = False ) :
    """Convert a solution to medium .
 Arguments
 exchanges : list of cobra . reaction
 The exchange reactions to consider .
 tolerance : positive double
 The absolute tolerance for fluxes . Fluxes with an absolute value
 smaller than this number will be ignored .
 exports : bool
 Whether to return export fluxes as well .
 Returns
 pandas . Series
 The " medium " , meaning all active import fluxes in the solution ."""

implementation:
LOGGER . debug ( "Formatting medium." )
medium = pd . Series ( )
for rxn in exchanges :
    export = len ( rxn . reactants ) == 1
    flux = rxn . flux
    if abs ( flux ) < tolerance :
        continue
    if export :
        medium [ rxn . id ] = - flux
    elif not export :
        medium [ rxn . id ] = flux
if not exports :
    medium = medium [ medium > 0 ]
return medium


signature:
def minimal_medium ( model , min_objective_value = 0.1 , exports = False , minimize_components = False , open_exchanges = False ) :
    """Find the minimal growth medium for the model .
 Finds the minimal growth medium for the model which allows for
 model as well as individual growth . Here , a minimal medium can either
 be the medium requiring the smallest total import flux or the medium
 requiring the least components ( ergo ingredients ) , which will be much
 slower due to being a mixed integer problem ( MIP ) .
 Arguments
 model : cobra . model
 The model to modify .
 min _ objective _ value : positive float or array - like object
 The minimum growth rate ( objective ) that has to be achieved .
 exports : boolean
 Whether to include export fluxes in the returned medium . Defaults to
 False which will only return import fluxes .
 minimize _ components : boolean or positive int
 Whether to minimize the number of components instead of the total
 import flux . Might be more intuitive if set to True but may also be
 slow to calculate for large communities . If set to a number ` n ` will
 return up to ` n ` alternative solutions all with the same number of
 components .
 open _ exchanges : boolean or number
 Whether to ignore currently set bounds and make all exchange reactions
 in the model possible . If set to a number all exchange reactions will
 be opened with ( - number , number ) as bounds .
 Returns
 pandas . Series , pandas . DataFrame or None
 A series giving the import flux for each required import
 reaction and ( optionally ) the associated export fluxes . All exchange
 fluxes are oriented into the import reaction e . g . positive fluxes
 denote imports and negative fluxes exports . If ` minimize _ components `
 is a number larger 1 may return a DataFrame where each column is a
 minimal medium . Returns None if the minimization is infeasible
 ( for instance if min _ growth > maximum growth rate ) .
 Notes
 Due to numerical issues the ` minimize _ components ` option will usually only
 minimize the number of " large " import fluxes . Specifically , the detection
 limit is given by ` ` integrality _ tolerance * max _ bound ` ` where ` ` max _ bound ` `
 is the largest bound on an import reaction . Thus , if you are interested
 in small import fluxes as well you may have to adjust the integrality
 tolerance at first with
 ` model . solver . configuration . tolerances . integrality = 1e - 7 ` for instance .
 However , this will be * very * slow for large models especially with GLPK ."""

implementation:
exchange_rxns = find_boundary_types ( model , "exchange" )
if isinstance ( open_exchanges , bool ) :
    open_bound = 1000
else :
    open_bound = open_exchanges
with model as mod :
    if open_exchanges :
        LOGGER . debug ( "Opening exchanges for %d imports." , len ( exchange_rxns ) )
        for rxn in exchange_rxns :
            rxn . bounds = ( - open_bound , open_bound )
    LOGGER . debug ( "Applying objective value constraints." )
    obj_const = mod . problem . Constraint ( mod . objective . expression , lb = min_objective_value , name = "medium_obj_constraint" )
    mod . add_cons_vars ( [ obj_const ] )
    mod . solver . update ( )
    mod . objective = Zero
    LOGGER . debug ( "Adding new media objective." )
    tol = mod . solver . configuration . tolerances . feasibility
    if minimize_components :
        add_mip_obj ( mod )
        if isinstance ( minimize_components , bool ) :
            minimize_components = 1
        seen = set ( )
        best = num_components = mod . slim_optimize ( )
        if mod . solver . status != OPTIMAL :
            LOGGER . warning ( "Minimization of medium was infeasible." )
            return None
        exclusion = mod . problem . Constraint ( Zero , ub = 0 )
        mod . add_cons_vars ( [ exclusion ] )
        mod . solver . update ( )
        media = [ ]
        for i in range ( minimize_components ) :
            LOGGER . info ( "Finding alternative medium #%d." , ( i + 1 ) )
            vars = [ mod . variables [ "ind_" + s ] for s in seen ]
            if len ( seen ) > 0 :
                exclusion . set_linear_coefficients ( dict . fromkeys ( vars , 1 ) )
                exclusion . ub = best - 1
            num_components = mod . slim_optimize ( )
            if mod . solver . status != OPTIMAL or num_components > best :
                break
            medium = _as_medium ( exchange_rxns , tol , exports = exports )
            media . append ( medium )
            seen . update ( medium [ medium > 0 ] . index )
        if len ( media ) > 1 :
            medium = pd . concat ( media , axis = 1 , sort = True ) . fillna ( 0.0 )
            medium . sort_index ( axis = 1 , inplace = True )
        else :
            medium = media [ 0 ]
    else :
        add_linear_obj ( mod )
        mod . slim_optimize ( )
        if mod . solver . status != OPTIMAL :
            LOGGER . warning ( "Minimization of medium was infeasible." )
            return None
        medium = _as_medium ( exchange_rxns , tol , exports = exports )
return medium


signature:
def _init_worker ( model , loopless , sense ) :
    """Initialize a global model object for multiprocessing ."""

implementation:
global _model
global _loopless
_model = model
_model . solver . objective . direction = sense
_loopless = loopless