def main():
    opt_parser = flags.MakeOpts()
    options, _ = opt_parser.parse_args(sys.argv)
    estimators = LoadAllEstimators()
    
    print ('Parameters: T=%f K, pH=%.2g, pMg=%.2g, '
           'I=%.2gmM, Median concentration=%.2gM' % 
           (default_T, options.ph, options.pmg, options.i_s, options.c_mid))

    for thermo in estimators.values():
        thermo.c_mid = options.c_mid
        thermo.pH = options.ph
        thermo.pMg = options.pmg
        thermo.I = options.i_s
        thermo.T = default_T
    
    kegg = Kegg.getInstance()
    while True:
        cid = GetReactionIdInput()        
        compound = kegg.cid2compound(cid)
        print 'Compound Name: %s' % compound.name
        print '\tKegg ID: C%05d' % cid
        print '\tFormula: %s' % compound.formula
        print '\tInChI: %s' % compound.inchi
        for key, thermo in estimators.iteritems():
            print "\t<< %s >>" % key
            try:
                print thermo.cid2PseudoisomerMap(cid),
                print '--> dG0\'f = %.1f kJ/mol' % compound.PredictFormationEnergy(thermo)
            except Exception as e: 
                print '\t\tError: %s' % (str(e))
Esempio n. 2
0
def CalculateThermo():
    estimators = LoadAllEstimators()
    parser = MakeOpts(estimators)
    options, _ = parser.parse_args(sys.argv)
    if options.csv_input_filename is None and options.cids is None:
        sys.stderr.write(parser.get_usage())
        sys.exit(-1)
    
    estimator = estimators[options.thermodynamics_source]
    pH, I, pMg, T = options.pH, options.I, options.pMg, options.T
    estimator.SetConditions(pH=pH, I=I, pMg=pMg, T=T)

    if options.csv_output_filename is not None:
        out_fp = open(options.csv_output_filename, 'w')
        print "writing results to %s ... " % options.csv_output_filename
    else:
        out_fp = sys.stdout
    
    if options.csv_input_filename is not None:
        csv_reader = csv.reader(open(options.csv_input_filename, 'r'))
        headers = csv_reader.next()
        cid_index = headers.index('kegg id')
        csv_rows = list(csv_reader)
    else:
        headers = ['kegg id']
        cid_index = 0
        csv_rows = [[c] for c in options.cids.split(',')]
        
    cids = []
    for row in csv_rows:
        try:
            cids.append(int(row[cid_index][1:]))
        except ValueError:
            continue
        except IndexError:
            continue

    csv_writer = csv.writer(out_fp)
    if options.biochemical:
        csv_writer.writerow(headers + ['dG0\'', 'pH', 'I', 'pMg', 'T'])
    else:
        csv_writer.writerow(headers + ['dG0', 'nH', 'z', 'nMg'])
        
    if options.biochemical:
        dG0_f_prime = estimator.GetTransformedFormationEnergies(cids)
        for i, cid in enumerate(cids):
            csv_writer.writerow(csv_rows[i] + [str(dG0_f_prime[0, i]), pH, I, pMg, T])
    else:
        for i, cid in enumerate(cids):
            try:
                for nH, z, nMg, dG0 in estimator.cid2PseudoisomerMap(cid).ToMatrix():
                    csv_writer.writerow(csv_rows[i] + [dG0, nH, z, nMg])
            except MissingCompoundFormationEnergy as e:
                csv_writer.writerow(csv_rows[i] + ['nan', str(e)])
def ExportThermo():
    estimators = LoadAllEstimators()
    options, _ = MakeOpts(estimators).parse_args(sys.argv)
    thermo = estimators[options.thermodynamics_source]

    print 'Thermodynamic source:', thermo.name
    print 'CSV output filename:', options.csv_out_fname

    cids, atom_matrix = CreateElementMatrix(thermo)
    rowdicts, fieldnames = FindRedoxPairs(cids, atom_matrix, thermo)
    csv_out = csv.DictWriter(open(options.csv_out_fname, 'w'), fieldnames)
    csv_out.writeheader()
    csv_out.writerows(rowdicts)
Esempio n. 4
0
def main():
    options, _ = flags.MakeOpts().parse_args(sys.argv)
    kegg = Kegg.getInstance()
    estimators = LoadAllEstimators()
    
    print ('Parameters: T=%f K, pH=%.2g, pMg=%.2g, '
           'I=%.2gmM, Median concentration=%.2gM' % 
           (default_T, options.ph, options.pmg, options.i_s, options.c_mid))

    for thermo in estimators.values():
        thermo.c_mid = options.c_mid
        thermo.pH = options.ph
        thermo.pMg = options.pmg
        thermo.I = options.i_s
        thermo.T = default_T
    
    cmap = {}
    if not options.ignore_cofactors:
        print 'Fixing concentrations of co-factors'
        cmap = reversibility.GetConcentrationMap()
    else:
        print 'Not fixing concentrations of co-factors'

    while True:
        rid = GetReactionIdInput()        
        reaction = kegg.rid2reaction(rid)
        print 'Reaction Name: %s' % reaction.name
        print '\tKegg ID: R%05d' % rid
        print '\tEC: %s' % str(reaction.ec_list)
        for key, thermo in estimators.iteritems():
            print "\t<< %s >>" % key
            try:
                print '\t\tdG0\'f = %.1f kJ/mol' % reaction.PredictReactionEnergy(thermo)
                rev = reversibility.CalculateReversability(reaction, thermo, concentration_map=cmap)
                print '\t\tgamma = %.3g' % rev
            except Exception as e: 
                print '\tError: %s' % (str(e))
def ExportJSONFiles():
    estimators = LoadAllEstimators()
    options, _ = MakeOpts(estimators).parse_args(sys.argv)

    thermo = estimators[options.thermodynamics_source]
    print "Using the thermodynamic estimations of: " + thermo.name

    # Make sure we have all the data.
    kegg = Kegg.getInstance()
    kegg.AddThermodynamicData(estimators['alberty'], priority=1)
    kegg.AddThermodynamicData(thermo, priority=2)

    db = SqliteDatabase('../res/gibbs.sqlite')
    kegg.AddGroupVectorData(db, table_name='pgc_groupvector')

    print 'Exporting KEGG compound pseudoisomers as JSON.'
    WriteJSONFile(kegg.AllCompounds(), options.out_filename)
Esempio n. 6
0
def ExportThermo():
    estimators = LoadAllEstimators()
    options = MakeOpts(estimators).parse_args()
    thermo = estimators[options.thermodynamics_source]

    print 'Thermodynamic source:', thermo.name
    print 'CSV output filename:', options.csv_out_filename

    thermo.SetConditions(pH=options.ph,
                         I=options.ionic_strength,
                         pMg=options.pmg,
                         T=options.temperature)
    if options.output_type == 'reaction':
        thermo.WriteBiochemicalReactionEnergiesToCsv(options.csv_out_filename)
    elif options.output_type == 'formation':
        thermo.WriteBiochemicalFormationEnergiesToCsv(options.csv_out_filename)
    else:
        thermo.WriteChemicalFormationEnergiesToCsv(options.csv_out_filename)
Esempio n. 7
0
def CalculateThermo():
    estimators = LoadAllEstimators()
    parser = MakeOpts(estimators)
    options, args = parser.parse_args(sys.argv)

    kegg = Kegg.getInstance()
    if options.rid is None:
        reaction = GetSparseReactionInput(args[-1], kegg)
    else:
        reaction = kegg.rid2reaction(options.rid)

    estimator = estimators[options.thermodynamics_source]
    pH, I, pMg, T = options.pH, options.I, options.pMg, options.T
    estimator.SetConditions(pH=pH, I=I, pMg=pMg, T=T)

    print "Thermodynamic source:", options.thermodynamics_source
    print('Parameters: pH=%.1f, pMg=%.1f, I=%.2fM, T=%.1fK' %
          (options.pH, options.pMg, options.I, options.T))
    print str(reaction)
    print 'dG\'0 = %.2f [kJ/mol]' % reaction.PredictReactionEnergy(estimator)
Esempio n. 8
0
def CalculateThermo():
    estimators = LoadAllEstimators()
    parser = MakeOpts(estimators)
    options, _ = parser.parse_args(sys.argv)
    if options.input_filename is None:
        sys.stderr.write(parser.get_usage())
        sys.exit(-1)

    estimator = estimators[options.thermodynamics_source]

    pH, I, pMg, T = options.pH, options.I, options.pMg, options.T
    kegg = Kegg.getInstance()

    if options.csv_output_filename is not None:
        out_fp = open(options.csv_output_filename, 'w')
        print "writing results to %s ... " % options.csv_output_filename
    else:
        out_fp = sys.stdout

    entry2fields_map = ParsedKeggFile.FromKeggFile(options.input_filename)
    all_reactions = []
    for key in sorted(entry2fields_map.keys()):
        field_map = entry2fields_map[key]
        p_data = PathwayData.FromFieldMap(field_map)
        if p_data.skip:
            continue

        cid_mapping = p_data.cid_mapping
        field_map = p_data.field_map
        _, _, _, reactions = kegg.parse_explicit_module_to_reactions(
            field_map, cid_mapping)
        all_reactions += reactions
    S, cids = kegg.reaction_list_to_S(all_reactions)
    dG0_r = estimator.GetTransfromedReactionEnergies(S, cids)

    csv_writer = csv.writer(out_fp)
    csv_writer.writerow(['reaction', 'dG0\'', 'pH', 'I', 'pMg', 'T'])

    for r, reaction in enumerate(all_reactions):
        csv_writer.writerow(
            [reaction.FullReactionString(), dG0_r[r, 0], pH, I, pMg, T])
Esempio n. 9
0
def ExportCSVFiles():
    estimators = LoadAllEstimators()
    options, _ = MakeOpts(estimators).parse_args(sys.argv)

    print "Using the thermodynamic estimations of: " + options.thermo_estimator
    thermo = estimators[options.thermo_estimator]
    thermo.pH = float(options.pH)
    thermo.I = float(options.I)
    thermo.pMg = float(options.pMg)
    thermo.T = float(options.T)

    # Make sure we have all the data.
    kegg = Kegg.getInstance()

    print 'Exporting KEGG compounds as JSON.'
    WriteCompoundCSV(kegg.AllCompounds(), thermo,
                     options.compounds_out_filename)

    print 'Exporting KEGG reactions as JSON.'
    WriteReactionCSV(kegg.AllReactions(), thermo,
                     options.reactions_out_filename)
Esempio n. 10
0
def main():
    estimators = LoadAllEstimators()
    args, _ = MakeOpts(estimators).parse_args(sys.argv)
    
    # Make sure we have all the data.
    db = SqliteDatabase('../res/gibbs.sqlite')
    G = GroupContribution(db=db, html_writer=NullHtmlWriter(),
                          transformed=args.transformed)
    G.init()
    
    print 'Exporting KEGG compounds to %s' % args.compounds_out_filename
    csv_writer = csv.writer(open(args.compounds_out_filename, 'w'))
    csv_writer.writerow(["KEGG ID", "nH", "CHARGE", "nMg", "dG0_f"])
    for cid in sorted(G.get_all_cids()):
        try:
            for nH, z, nMg, dG0 in G.cid2PseudoisomerMap(cid).ToMatrix():
                csv_writer.writerow(["C%05d" % cid, nH, z, nMg, "%.1f" % dG0])
        except MissingCompoundFormationEnergy as e:
            csv_writer.writerow(["C%05d" % cid, None, None, None, str(e)])
        
    print 'Exporting KEGG reactions to %s' % args.reactions_out_filename
    csv_writer = csv.writer(open(args.reactions_out_filename, 'w'))
    csv_writer.writerow(["KEGG ID", "dG'0_r (pH=%.1f, I=%.2f, pMg=%.1f, T=%.1f)" % 
                         (args.ph, args.i_s, args.pmg, args.temp)])
    for rid in sorted(G.kegg.get_all_rids()):
        reaction = G.kegg.rid2reaction(rid)
        try:
            reaction.Balance(balance_water=True)
            dG0_r = reaction.PredictReactionEnergy(G, pH=args.ph,
                        pMg=args.pmg, I=args.i_s, T=args.temp)
            csv_writer.writerow(["R%05d" % rid, "%.1f" % dG0_r])
        except (KeggParseException,
                MissingCompoundFormationEnergy, 
                KeggReactionNotBalancedException,
                MissingReactionEnergy,
                KeyError,
                OpenBabelError) as e:
            csv_writer.writerow(["R%05d" % rid, str(e)])
Esempio n. 11
0
def ExportJSONFiles():
    estimators = LoadAllEstimators()
    options, _ = MakeOpts(estimators).parse_args(sys.argv)

    thermo_list = []
    thermo_list.append(estimators[options.thermodynamics_source])
    thermo_list.append(
        PsuedoisomerTableThermodynamics.FromCsvFile(
            options.thermodynamics_csv))

    # Make sure we have all the data.
    kegg = Kegg.getInstance()
    for i, thermo in enumerate(thermo_list):
        print "Priority %d - formation energies of: %s" % (i + 1, thermo.name)
        kegg.AddThermodynamicData(thermo, priority=(i + 1))

    db = SqliteDatabase('../res/gibbs.sqlite')

    print 'Exporting Group Contribution Nullspace matrix as JSON.'
    nullspace_vectors = []
    for row in db.DictReader('ugc_conservations'):
        d = {'msg': row['msg']}
        sparse = json.loads(row['json'])
        d['reaction'] = []
        for cid, coeff in sparse.iteritems():
            d['reaction'].append([coeff, "C%05d" % int(cid)])
        nullspace_vectors.append(d)
    WriteJSONFile(nullspace_vectors, options.nullspace_out_filename)

    print 'Exporting KEGG compounds as JSON.'
    WriteJSONFile(kegg.AllCompounds(), options.compounds_out_filename)

    print 'Exporting KEGG reactions as JSON.'
    WriteJSONFile(kegg.AllReactions(), options.reactions_out_filename)

    print 'Exporting KEGG enzymes as JSON.'
    WriteJSONFile(kegg.AllEnzymes(), options.enzymes_out_filename)
Esempio n. 12
0
def main():
    kegg = Kegg.getInstance()
    options, args = MakeOpts().parse_args(sys.argv)
    print ('Parameters: T=%f K, pMg=%.2g, I=%.2gM' % 
           (options.T, options.pMg, options.I))
    print "reaction:", args[-1]

    estimators = LoadAllEstimators()
    
    plt.rcParams['legend.fontsize'] = 8
    plt.rcParams['font.family'] = 'sans-serif'
    plt.rcParams['font.size'] = 12
    plt.rcParams['lines.linewidth'] = 2
    
    colormap = {}
    colormap['markers'] = (64.0/255, 111.0/255, 29.0/255, 3.0)
    #colormap['hatzi_gc'] = (54.0/255, 182.0/255, 202.0/255, 1.0)
    colormap['UGC'] = (202.0/255, 101.0/255, 54.0/255, 1.0)
    #colormap['alberty'] = (202.0/255, 54.0/255, 101.0/255, 1.0)
    colormap['PGC'] = (101.0/255, 202.0/255, 54.0/255, 1.0)
    
    fig = plt.figure(figsize=(6,6), dpi=90)
    
    fig.hold(True)
    if options.rid is None:
        reaction = GetSparseReactionInput(args[-1], kegg)
    else:
        reaction = kegg.rid2reaction(options.rid)
    reaction.Balance()
    print 'Reaction: %s' % reaction.FullReactionString()

    nist = Nist()
    nist_rows = nist.SelectRowsFromNist(reaction, check_reverse=True)

    pH_min = 7.0 - options.pH/2.0
    pH_max = 7.0 + options.pH/2.0
    
    if nist_rows:
        dG0_list = []
        pH_list = []
        for row_data in nist_rows:
            pH_list.append(row_data.pH)
            if row_data.reaction == reaction:
                dG0_list.append(row_data.dG0_r)
            else:
                dG0_list.append(-row_data.dG0_r)
    
        plt.plot(pH_list, dG0_list, marker='.', linestyle='none',
                   label='measured data', markeredgecolor='none',
                   markerfacecolor=colormap['markers'], markersize=5)
        pH_max = max(pH_list + [pH_max])
        pH_min = min(pH_list + [pH_min])
    
    pH_range = np.arange(pH_min-0.1, pH_max+0.1, 0.02)
    for key, thermo in estimators.iteritems():
        if key not in colormap:
            continue
        print key, 'dG0 at pH=7: %.2f' % reaction.PredictReactionEnergy(thermo, 
                pH=7.0, pMg=options.pMg, I=options.I, T=options.T)
        dG0 = []
        for pH in pH_range:
            dG0.append(reaction.PredictReactionEnergy(thermo, 
                pH=pH, pMg=options.pMg, I=options.I, T=options.T))
        plt.plot(pH_range, dG0, marker='None', linestyle='solid', color=colormap[key],
                   figure=fig, label=thermo.name)

    plt.xlabel('pH')
    plt.ylabel(r'$\Delta_r G^\circ$ [kJ/mol]')
    plt.title(kegg.reaction2string(reaction), fontsize=8)
    plt.legend(loc='lower left')

    if not options.output:
        plt.tight_layout()
        plt.show()
    else:
        fig.savefig(options.output, format='svg')