def python_main():
    logger = logging.getLogger('')
    logger.setLevel(logging.INFO)
    from python.component_contribution import ComponentContribution
    from python.kegg_model import KeggModel
    from python.thermodynamic_constants import default_RT

    cc = ComponentContribution.init()
    reaction_strings = open(REACTION_FNAME, 'r').readlines()
    model = KeggModel.from_formulas(reaction_strings)

    model.add_thermo(cc)
    dG0_prime, dG0_std = model.get_transformed_dG0(7.0, 0.2, 298.15)
    
    cid2c_range = {cid : (1e-6, 1e-2) for cid in model.cids}
    cid2c_range['C00001'] = (1.0, 1.0) # water must be always set to 1 (equivalent to 55M)
    
    ln_conc = np.log(np.matrix([cid2c_range[cid] for cid in model.cids]))
    ln_conc_min = ln_conc[:, 0]
    ln_conc_max = ln_conc[:, 1]
    
    S_minus, S_plus = model.get_unidirectional_S()
    
    dG_prime_min = dG0_prime + default_RT * (S_minus.T * ln_conc_max + S_plus.T * ln_conc_min)
    dG_prime_max = dG0_prime + default_RT * (S_minus.T * ln_conc_min + S_plus.T * ln_conc_max)
    
    for i, r in enumerate(reaction_strings):
        print '-'*50
        print r.strip()
        print "dG'0      = %8.1f +- %5.1f" % (dG0_prime[i, 0], dG0_std[i, i] * 1.96)
        print "dG' range = %8.1f  - %8.1f" % (dG_prime_min[i, 0], dG_prime_max[i, 0])
        if dG_prime_min[i, 0] < 0 and dG_prime_max[i, 0] > 0:
            print "REVERSIBLE!"
        else:
            print "IRREVERSIBLE!"
def main():

    td = TrainingData()
    cc = ComponentContribution.init()

    G1 = np.matrix(cc.params['G1'])
    G2 = np.matrix(cc.params['G2'])
    G3 = np.matrix(cc.params['G3'])

    ############################################################################

    #reaction = KeggReaction.parse_formula('C00002 + C00001 <=> C00008 + C00009'); fname = 'atpase';
    reaction = KeggReaction.parse_formula('C00149 <=> C00122 + C00001'); fname = 'fumarase';

    x, g = cc._decompose_reaction(reaction)
    weights_rc = (x.T * G1).round(5)
    weights_gc = (x.T * G2 + g.T * G3).round(5)
    weights = weights_rc + weights_gc
    orders = sorted(range(weights.shape[1]),
                    key=lambda j:abs(weights[0, j]), reverse=True)

    output = csv.writer(open('res/%s_analysis.csv' % fname, 'w'))
    output.writerow(('Weight', 'dG\'0', 'dG0', 'reference', 'reaction'))
    for j in orders:
        if abs(weights[0, j]) < 1e-7:
            continue
                              
        output.writerow((weights_rc[0, j], td.dG0_prime[j], td.dG0[j],
                         td.reference[j], td.description[j]))
def python_main():
    logger = logging.getLogger("")
    logger.setLevel(logging.INFO)
    from python.component_contribution import ComponentContribution
    from python.kegg_model import KeggModel

    cc = ComponentContribution.init()
    reaction_strings = open(REACTION_FNAME, "r").readlines()
    model = KeggModel.from_formulas(reaction_strings)
    model.add_thermo(cc)

    dG0_prime, dG0_std = model.get_transformed_dG0(7.0, 0.2, 298.15)

    print "For a linear problem, define two vector variables 'x' and 'y', each of length Nr (i.e. " + "the same length as the list of reactions). Then add these following " + "constraints: \n" + "-1 <= y <= 1\n" + "x = dG0_prime + 3 * dG0_std * y\n" + "Then use 'x' as the value of the standard Gibbs energy for all reactions."
    print "The results are writteng to: " + OUTPUT_FNAME

    savemat(OUTPUT_FNAME, {"dG0_prime": dG0_prime, "dG0_std": dG0_std}, oned_as="row")
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 23 14:58:44 2014

@author: eladn
"""
from python.component_contribution import ComponentContribution
from python.kegg_reaction import KeggReaction

#pH = 7
I = 0.2
T = 298.15
F = 96.48 / 1000.0 # kJ/mol / mV
cc = ComponentContribution.init()

#formula = 'C00033 + C00282 <=> C00084 + C00001'
#formula = 'C00067 + C00001 <=> C00058 + C00010'
formula = 'C00003 + C00282 <=> C00004'
#############################################################################
reaction = KeggReaction.parse_formula(formula)
reaction_atom_bag = reaction._get_reaction_atom_bag()
n_e = 0
if 'e-' in reaction_atom_bag:
    n_e = reaction_atom_bag['e-']
    del reaction_atom_bag['e-']
if len(reaction_atom_bag) != 0:
    raise Exception('Reaction is not balanced (not only with respect to e-)')

dG0_r, u_r = cc.get_dG0_r(reaction)

for pH in xrange(6, 9):
import csv, os
import numpy as np
import matplotlib.pyplot as plt
from python.component_contribution import ComponentContribution
from python.kegg_model import KeggModel

REPORT_CACHE_FNAME = 'cache/report_gc.csv'
cid2dG0 = {}
if not os.path.exists(REPORT_CACHE_FNAME):
    fp = open(REPORT_CACHE_FNAME, 'w')
    cc = ComponentContribution()
    cc.train()
    csv_out = csv.writer(fp)
    csv_out.writerow(['cid', 'dG0_f'])
    for compound_id in cc.ccache.get_all_compound_ids():
        dG0_f = cc.get_major_ms_dG0_f(compound_id)
        csv_out.writerow([compound_id, '%8.2f' % dG0_f])
        cid2dG0[compound_id] = dG0_f
else:
    for row in csv.DictReader(open(REPORT_CACHE_FNAME, 'r')):
        cid2dG0[row['cid']] = float(row['dG0_f'])

REACTION_FNAME = 'tests/report_gc_reactions.txt'
reaction_strings = open(REACTION_FNAME, 'r').readlines()
model = KeggModel.from_formulas(reaction_strings)    

# compare the dG0_r of the model to the one we get if multiplying
# the model stoichiometric matrix by the formation energies
model_dG0_f = np.matrix([cid2dG0[cid] for cid in model.cids]).T
model_dG0_r = model.S.T * model_dG0_f