Exemplo n.º 1
0
def AnalyzeConcentrationGradient(prefix,
                                 thermo,
                                 csv_output_fname,
                                 cid=13):  # default compound is PPi
    compound_name = thermo.kegg.cid2name(cid)
    kegg_file = ParsedKeggFile.FromKeggFile('../data/thermodynamics/%s.txt' %
                                            prefix)
    html_writer = HtmlWriter('../res/%s.html' % prefix)
    null_html_writer = NullHtmlWriter()
    if csv_output_fname:
        csv_output = csv.writer(open(csv_output_fname, 'w'))
        csv_output.writerow(['pH', 'I', 'T', '[C%05d]' % cid] +
                            kegg_file.entries())
    else:
        csv_output = None

    pH_vec = np.array(
        [7])  # this needs to be fixed so that the txt file will set the pH
    conc_vec = 10**(-np.arange(2, 6.0001, 0.25)
                    )  # logarithmic scale between 10mM and 1nM
    override_bounds = {}

    fig = plt.figure(figsize=(6, 6), dpi=90)
    legend = []
    for pH in pH_vec.flat:
        obd_vec = []
        for conc in conc_vec.flat:
            override_bounds[cid] = (conc, conc)
            logging.info("pH = %g, [%s] = %.1e M" % (pH, compound_name, conc))
            data, labels = pareto(kegg_file,
                                  null_html_writer,
                                  thermo,
                                  pH=pH,
                                  section_prefix="",
                                  balance_water=True,
                                  override_bounds=override_bounds)
            obd_vec.append(data[:, 1])
            csv_output.writerow([pH, thermo.I, thermo.T, conc] +
                                list(data[:, 1].flat))
        obd_mat = np.matrix(
            obd_vec)  # rows are pathways and columns are concentrations
        plt.plot(conc_vec, obd_mat, '.-', figure=fig)
        legend += ['%s, pH = %g' % (l, pH) for l in labels]

    plt.title("ODB vs. [%s] (I = %gM, T = %gK)" %
              (compound_name, thermo.I, thermo.T),
              figure=fig)
    plt.xscale('log')
    plt.xlabel('Concentration of %s [M]' % thermo.kegg.cid2name(cid),
               figure=fig)
    plt.ylabel('Optimized Distributed Bottleneck [kJ/mol]', figure=fig)
    plt.legend(legend)
    html_writer.write('<h2 id="figure_%s">Summary figure</h1>\n' % prefix)
    html_writer.embed_matplotlib_figure(fig, name=prefix)

    html_writer.close()
Exemplo n.º 2
0
def main():
    html_writer = HtmlWriter("../res/formation_resolve.html")
    estimators = LoadAllEstimators()
    for name in ['alberty']:
        thermo = estimators[name]
        nist = Nist()
        nist.verify_formation(html_writer=html_writer, 
                              thermodynamics=thermo,
                              name=name)
    html_writer.close()
Exemplo n.º 3
0
def test_single_modules(mids):
    from pygibbs.groups import GroupContribution
    db = SqliteDatabase('../res/gibbs.sqlite')
    html_writer = HtmlWriter("../res/thermodynamic_module_analysis.html")
    gc = GroupContribution(db, html_writer)
    gc.init()

    for mid in mids:
        html_writer.write("<h2>M%05d</h2>\n" % mid)
        S, rids, fluxes, cids = gc.kegg.get_module(mid)
        thermodynamic_pathway_analysis(S, rids, fluxes, cids, gc, html_writer)
Exemplo n.º 4
0
def AnalyzePareto(pathway_file, output_prefix, thermo, pH=None):
    pathway_list = KeggFile2PathwayList(pathway_file)
    pathway_names = [entry for (entry, _) in pathway_list]
    html_writer = HtmlWriter('%s.html' % output_prefix)
    xls_workbook = Workbook()

    logging.info("running OBD analysis for all pathways")
    data = GetAllOBDs(pathway_list,
                      html_writer,
                      thermo,
                      pH=pH,
                      section_prefix="pareto",
                      balance_water=True,
                      override_bounds={})

    for d in data:
        sheet = xls_workbook.add_sheet(d['entry'])
        sheet.write(0, 0, "reaction")
        sheet.write(0, 1, "formula")
        sheet.write(0, 2, "flux")
        sheet.write(0, 3, "delta_r G'")
        sheet.write(0, 4, "shadow price")
        for r, rid in enumerate(d['rids']):
            sheet.write(r + 1, 0, rid)
            sheet.write(r + 1, 1, d['formulas'][r])
            sheet.write(r + 1, 2, d['fluxes'][0, r])
            sheet.write(r + 1, 3, d['dG_r_prime'][0, r])
            sheet.write(r + 1, 4, d['reaction prices'][r, 0])

    xls_workbook.save('%s.xls' % output_prefix)

    obds = []
    minus_avg_tg = []
    for i, d in enumerate(data):
        obds.append(d['OBD'])
        if d['sum of fluxes']:
            minus_avg_tg.append(-d['max total dG'] / d['sum of fluxes'])
        else:
            minus_avg_tg.append(0)

    fig = plt.figure(figsize=(6, 6), dpi=90)
    plt.plot(minus_avg_tg, obds, 'o', figure=fig)
    plt.plot([0, max(minus_avg_tg)], [0, max(minus_avg_tg)], '--g')
    for i, name in enumerate(pathway_names):
        plt.text(minus_avg_tg[i], obds[i], name)
    plt.title('OBD vs. Average $\Delta_r G$')
    plt.ylim(ymin=0)
    plt.xlim(xmin=0)
    plt.xlabel(r'- Average $\Delta_r G$ [kJ/mol]')
    plt.ylabel(r'Optimized Distributed Bottleneck [kJ/mol]')
    html_writer.write('<h2>Pareto figure</h1>\n')
    html_writer.embed_matplotlib_figure(fig)
    html_writer.close()
Exemplo n.º 5
0
def compare_charges():
    #db_public = SqliteDatabase('../data/public_data.sqlite')
    db_gibbs = SqliteDatabase('../res/gibbs.sqlite')
    print "Writing Compare Charges report to ../res/groups_report.html"
    html_writer = HtmlWriter("../res/groups_report.html")
    kegg = Kegg.getInstance()

    #pH, I, pMg, T = default_pH, default_I, default_pMg, default_T
    pH, I, pMg, T = default_pH, 0, 14, default_T

    cid2error = {}
    for row_dict in db_gibbs.DictReader("gc_errors"):
        cid = int(row_dict['cid'])
        cid2error[cid] = row_dict['error']

    estimators = {}
    estimators['hatzi'] = Hatzi(use_pKa=False)
    estimators['milo'] = PsuedoisomerTableThermodynamics.FromDatabase(
        db_gibbs, 'gc_pseudoisomers', name='Milo Group Contribution')

    all_cids = set(lsum([e.get_all_cids() for e in estimators.values()]))
    dict_list = []
    for cid in all_cids:
        try:
            name = kegg.cid2name(cid)
            link = kegg.cid2compound(cid).get_link()
        except KeyError:
            name = "unknown"
            link = ""
        row_dict = {
            'cid': '<a href="%s">C%05d</a>' % (link, cid),
            'name': name,
            'error': cid2error.get(cid, None)
        }
        for key, est in estimators.iteritems():
            try:
                pmap = est.cid2PseudoisomerMap(cid)
                dG0, dG0_tag, nH, z, nMg = pmap.GetMostAbundantPseudoisomer(
                    pH, I, pMg, T)
            except MissingCompoundFormationEnergy:
                dG0, dG0_tag, nH, z, nMg = "", "", "", "", ""
            row_dict['nH_' + key] = nH
            row_dict['charge_' + key] = z
            row_dict['nMg_' + key] = nMg
            row_dict['dG0_' + key] = dG0
            row_dict['dG0_tag_' + key] = dG0_tag
        dict_list.append(row_dict)

    html_writer.write_table(
        dict_list,
        headers=['cid', 'name', 'charge_hatzi', 'charge_milo', 'error'])
    html_writer.close()
Exemplo n.º 6
0
def example_reductive(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=15,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    add_redox_reactions(pl)
    r = Reaction.FromFormula("3 C00011 => C00022")
    #r.Balance()
    pl.find_path("reductive", r)
Exemplo n.º 7
0
def example_oxidative(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=10,
                    maximal_dG=0,
                    thermodynamic_method=OptimizationMethods.MAX_TOTAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    add_redox_reactions(pl, NAD_only=False)
    r = Reaction.FromFormula("C00022 => 3 C00011")
    #r.Balance()
    pl.find_path("oxidative", r)
Exemplo n.º 8
0
def runBeta2Alpha(thermo, reactionList):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/Beta2Alpha.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=15,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    add_redox_reactions(pl)
    for r in reactionList:
        pl.add_reaction(Reaction.FromFormula(r, "Auto generate #%s" % hash(r)))
    r = Reaction.FromFormula("C00099 => C01401")
    pl.find_path("Beta2Alpha", r)
Exemplo n.º 9
0
 def __init__(self, html_fname):
     self.serv = None
     self.db = SqliteDatabase('channeling/channeling.sqlite', 'w')
     self.html_writer = HtmlWriter(html_fname)
     
     self.COMPOUND_TABLE_NAME = 'kegg_compounds'
     self.GENE_TABLE_NAME = 'kegg_genes'
     self.GENE_REACTION_TABLE_NAME = 'kegg_genes_to_reactions'
     self.REACTION_TABLE_NAME = 'kegg_reactions'
     self.EQUATION_TABLE_NAME = 'kegg_equations'
     self.STOICHIOMETRY_TABLE_NAME = 'kegg_stoichiometry'
     self.GIBBS_ENERGY_TABLE_NAME = 'kegg_gibbs_energies'
     self.GENE_ENERGY_TABLE_NAME = 'kegg_gene_energies'
     self.FUNCTIONAL_INTERATCTIONS_TABLE = 'parkinson_functional_interactions'
     self.GENE_PAIRS_TABLE_NAME = 'kegg_gene_pairs'
     self.COFACTOR_TABLE_NAME = 'kegg_cofactors'
Exemplo n.º 10
0
def example_lower_glycolysis(thermo):
    
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=8,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    add_redox_reactions(pl)
    #r = Reaction.FromFormula("C00003 + C00118 + C00001 => C00022 + C00004 + C00009")
    r = Reaction.FromFormula("C00118 => C00022")
    #r.Balance()
    pl.find_path("GAP => PYR", r)
Exemplo n.º 11
0
def example_glycolysis(thermo):
    
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=15,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl, free_ATP_hydrolysis=False)
    ban_toxic_compounds(pl)
    #add_carbon_counts(pl)
    #r = Reaction.FromFormula("C00031 => 6 C06265")
    r = Reaction.FromFormula("C00031 + 3 C00008 => 2 C00186 + 3 C00002")
    #r.Balance()
    pl.find_path("GLC => 2 LAC, 3 ATP, No methylglyoxal", r)
Exemplo n.º 12
0
def example_three_acetate(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=20,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    #add_redox_reactions(pl)
    pl.delete_reaction(761) # F6P + Pi = E4P + acetyl-P
    pl.delete_reaction(1621) # X5P + Pi = GA3P + acetyl-P

    r = Reaction.FromFormula("C00031 => 3 C00033")
    #r.Balance()
    pl.find_path("three_acetate", r)
Exemplo n.º 13
0
def example_rpi_bypass(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=10,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    #add_redox_reactions(pl)
    pl.delete_reaction(1056) # ribose-phosphate isomerase
    pl.delete_reaction(1081) # ribose isomerase

    r = Reaction.FromFormula("C00117 => C01182")
    #r.Balance()
    pl.find_path("rpi_bypass", r)
Exemplo n.º 14
0
def example_glucose_to_ethanol_and_formate(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=15,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    #add_cofactor_reactions(pl)
    #add_XTP_reactions(pl, '=>')
    #add_redox_reactions(pl)
    #pl.delete_reaction(761) # F6P + Pi = E4P + acetyl-P
    #pl.delete_reaction(1621) # X5P + Pi = GA3P + acetyl-P

    r = Reaction.FromFormula("2 C00031 + 3 C00001 => 6 C00058 + 3 C00469")
    r.Balance()
    pl.find_path("glucose_to_ethanol_and_formate", r)
Exemplo n.º 15
0
def example_more_than_two_pyruvate(thermo):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=20,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    #add_cofactor_reactions(pl)
    #add_XTP_reactions(pl, '=>')
    #add_redox_reactions(pl)
    #pl.delete_reaction(761) # F6P + Pi = E4P + acetyl-P
    #pl.delete_reaction(1621) # X5P + Pi = GA3P + acetyl-P

    r = Reaction.FromFormula("3 C00031 + 3 C00011 + C00003 => 7 C00022 + 3 C00001 + C00004")
    r.Balance()
    pl.find_path("more_than_two_pyr", r)
Exemplo n.º 16
0
def main():
    options, _ = MakeOpts().parse_args(sys.argv)
    
    db = SqliteDatabase("../res/gibbs.sqlite")
    public_db = SqliteDatabase("../data/public_data.sqlite")
    output_filename = os.path.abspath(options.output_filename)
    logging.info('Will write output to %s' % output_filename)
    
    html_writer = HtmlWriter(output_filename)
    nist = Nist(T_range=None)
    nist_regression = NistRegression(db, html_writer=html_writer, nist=nist)
    nist_regression.std_diff_threshold = 5 # the threshold over which to print an analysis of a reaction
    #nist_regression.nist.T_range = None(273.15 + 24, 273.15 + 40)
    #nist_regression.nist.override_I = 0.25
    #nist_regression.nist.override_pMg = 14.0

    html_writer.write("<h2>NIST regression:</h2>")
    if options.use_prior:
        logging.info('Using the data from Alberty as fixed prior')
        prior_thermo = PsuedoisomerTableThermodynamics.FromDatabase(
            public_db, 'alberty_pseudoisomers', name="Alberty")
    else:
        prior_thermo = None
    html_writer.write('</br><b>Regression Tables</b>\n')
    html_writer.insert_toggle(start_here=True)
    nist_regression.Train(options.from_database, prior_thermo)
    html_writer.div_end()
 
    html_writer.write('</br><b>PRC results</b>\n')
    html_writer.insert_toggle(start_here=True)
    nist_regression.WriteDataToHtml(html_writer)
    html_writer.div_end()

    html_writer.write('</br><b>Transformed reaction energies - PRC vs. Observed</b>\n')
    html_writer.insert_toggle(start_here=True)
    N, rmse = nist_regression.VerifyResults()
    html_writer.div_end()
    
    logging.info("Regression results for transformed data:")
    logging.info("N = %d, RMSE = %.1f" % (N, rmse))

    html_writer.close()
Exemplo n.º 17
0
def main():
    estimators = LoadAllEstimators()
    parser = MakeArgParser(estimators)
    args = parser.parse_args()

    thermo = estimators[args.thermodynamics_source]

    kegg_file = ParsedKeggFile.FromKeggFile(args.config_fname)
    entries = kegg_file.entries()
    if len(entries) == 0:
        raise ValueError('No entries in configuration file')
    entry = 'CONFIGURATION'
    if entry not in entries:
        logging.warning(
            'Configuration file does not contain the entry "CONFIGURATION". '
            'Using the first entry by default: %s' % entries[0])
        entry = entries[0]
    p_data = PathwayData.FromFieldMap(kegg_file[entry])
    thermo.SetConditions(pH=p_data.pH, I=p_data.I, T=p_data.T, pMg=p_data.pMg)
    thermo.c_range = p_data.c_range
    bounds = p_data.GetBounds()

    html_writer = HtmlWriter(args.output_prefix + ".html")

    rowdicts = []
    headers = ['Module', 'Name', 'OBD [kJ/mol]', 'Length']
    kegg = Kegg.getInstance()
    for mid in kegg.get_all_mids():
        html_writer.write('<h2 id=M%05d>M%05d: %s</h2>' %
                          (mid, mid, kegg.get_module_name(mid)))
        try:
            d = AnalyzeKeggModule(thermo, mid, bounds, html_writer)
        except KeyError:
            continue
        d['Module'] = '<a href="#M%05d">M%05d</a>' % (mid, mid)
        d['Name'] = kegg.get_module_name(mid)
        rowdicts.append(d)

    rowdicts.sort(key=lambda x: x['OBD [kJ/mol]'])
    html_writer.write_table(rowdicts, headers, decimal=1)
    html_writer.close()
Exemplo n.º 18
0
def example_formate(thermo, product_cid=22, co2_conc=1e-5):
    co2_hydration = Reaction.FromFormula("C00011 + C00001 => C00288")
    co2_hydration_dG0_prime = float(thermo.GetTransfromedKeggReactionEnergies([co2_hydration]))
    carbonate_conc = co2_conc * np.exp(-co2_hydration_dG0_prime / (R*default_T))
    thermo.bounds[11] = (co2_conc, co2_conc)
    thermo.bounds[288] = (carbonate_conc, carbonate_conc)
    
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/pathologic.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=20,
                    maximal_dG=0.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl, free_ATP_hydrolysis=True)
    add_redox_reactions(pl, NAD_only=False)
   
    pl.delete_reaction(134) # formate:NADP+ oxidoreductase
    pl.delete_reaction(519) # Formate:NAD+ oxidoreductase
    pl.delete_reaction(24) # Rubisco
    pl.delete_reaction(581) # L-serine:NAD+ oxidoreductase (deaminating)
    pl.delete_reaction(220) # L-serine ammonia-lyase
    pl.delete_reaction(13) # glyoxylate carboxy-lyase (dimerizing; tartronate-semialdehyde-forming)
    pl.delete_reaction(585) # L-Serine:pyruvate aminotransferase
    pl.delete_reaction(1440) # D-Xylulose-5-phosphate:formaldehyde glycolaldehydetransferase
    pl.delete_reaction(5338) # 3-hexulose-6-phosphate synthase
    
    
    pl.add_reaction(Reaction.FromFormula("C06265 => C00011", name="CO2 uptake"))
    pl.add_reaction(Reaction.FromFormula("C06265 => C00288", name="carbonate uptake"))
    pl.add_reaction(Reaction.FromFormula("C06265 => C00058", name="formate uptake"))

    r = Reaction.FromFormula("5 C06265 + C00058 => C%05d" % product_cid) # at least one formate to product
    #r.Balance()
    
    kegg = Kegg.getInstance()
    pl.find_path("formate to %s" % kegg.cid2name(product_cid), r)
Exemplo n.º 19
0
def runPathologic(thermo, reactionList):
    pl = Pathologic(db=SqliteDatabase('../res/gibbs.sqlite', 'r'),
                    public_db=SqliteDatabase('../data/public_data.sqlite'),
                    html_writer=HtmlWriter('../res/mog_finder.html'),
                    thermo=thermo,
                    max_solutions=None,
                    max_reactions=15,
                    maximal_dG=-3.0,
                    thermodynamic_method=OptimizationMethods.GLOBAL,
                    update_file=None)
    add_cofactor_reactions(pl)
    add_redox_reactions(pl)
    for r in reactionList:
        pl.add_reaction(Reaction.FromFormula(r, "Auto generate #%s" % hash(r)))
    pl.delete_reaction(134)
    pl.delete_reaction(344)
    pl.delete_reaction(575)
    pl.delete_reaction(212)
    #pl.add_reaction(Reaction.FromFormula('C00149 + C00006 <=> C00036 + C00005 + C00080',
    #                                     'malate + NADP+ = oxaloacetate + NADPH',343))
    #pl.add_reaction(Reaction.FromFormula('C00222 + C00010 + C00006 <=> C00083 + C00005',
    #                                     'malonate-semialdehyde + CoA + NADP+ = malonyl-CoA + NADPH',740))
    r = Reaction.FromFormula("2 C00288 => C00048")
    pl.find_path("MOG_finder", r)
Exemplo n.º 20
0
                continue
            if self.override_pMg or self.override_I or self.override_T:
                nist_row_copy = nist_row_data.Clone()
                if self.override_pMg:
                    nist_row_copy.pMg = self.override_pMg
                if self.override_I:
                    nist_row_copy.I = self.override_I
                if self.override_T:
                    nist_row_copy.T = self.override_T
                rows.append(nist_row_copy)
            else:
                rows.append(nist_row_data)
        return rows

    def GetUniqueReactionSet(self):
        return set([row.reaction for row in self.data])


if __name__ == '__main__':
    #logging.getLogger('').setLevel(logging.DEBUG)
    _mkdir("../res/nist")
    html_writer = HtmlWriter("../res/nist/statistics.html")
    nist = Nist()
    fp = open('../res/nist_kegg_ids.txt', 'w')
    for cid in nist.GetAllCids():
        fp.write("C%05d\n" % cid)
    fp.close()
    nist.AnalyzeStats(html_writer)
    nist.AnalyzeConnectivity(html_writer)
    html_writer.close()
Exemplo n.º 21
0
    #print m.ToFormat('mol')
    #print m.ToFormat('mol2')
    #print m.ToFormat('smi')
    #print m.ToFormat('inchi')
    #print m.ToFormat('sdf')

    diss_table = Molecule._GetDissociationTable('C(=O)(O)CN',
                                                fmt='smiles',
                                                mid_pH=default_pH,
                                                min_pKa=0,
                                                max_pKa=14,
                                                T=default_T)
    print "glycine\n", diss_table

    html_writer = HtmlWriter('../res/molecule.html')
    from pygibbs.kegg import Kegg
    kegg = Kegg.getInstance()
    html_writer.write('<h1>pKa estimation using ChemAxon</h1>\n')
    for cid in [41]:
        m = kegg.cid2mol(cid)
        html_writer.write("<h2>C%05d : %s</h2>\n" % (cid, str(m)))
        diss_table = m.GetDissociationTable()
        pmap = diss_table.GetPseudoisomerMap()
        diss_table.WriteToHTML(html_writer)
        pmap.WriteToHTML(html_writer)
        html_writer.write("</p>\n")
        #print m.GetDissociationConstants()
        #print m.GetMacrospecies()

    #obmol = m.ToOBMol()
Exemplo n.º 22
0
    return parser


if __name__ == '__main__':
    parser = MakeOpts()
    args = parser.parse_args()
    util._mkdir('../res')
    db = SqliteDatabase('../res/gibbs.sqlite', 'w')

    if args.transformed:
        prefix = 'bgc'
    else:
        prefix = 'pgc'

    if args.test_only:
        html_writer = HtmlWriter('../res/%s_test.html' % prefix)
    elif args.train_only:
        html_writer = HtmlWriter('../res/%s_train.html' % prefix)
    else:
        html_writer = HtmlWriter('../res/%s.html' % prefix)

    G = GroupContribution(db=db,
                          html_writer=html_writer,
                          transformed=args.transformed)

    G.LoadGroups(FromDatabase=args.from_database, FromFile=args.groups_species)
    G.LoadObservations(args.from_database)
    G.LoadGroupVectors(args.from_database)

    if args.test_only:
        G.LoadContributionsFromDB()
Exemplo n.º 23
0
    args, _ = MakeOpts(estimators).parse_args(sys.argv)
    input_filename = os.path.abspath(args.input_filename)
    output_filename = os.path.abspath(args.output_filename)
    if not os.path.exists(input_filename):
        logging.fatal('Input filename %s doesn\'t exist' % input_filename)
        
    print 'Will read pathway definitions from %s' % input_filename
    print 'Will write output to %s' % output_filename
    
    db_loc = args.db_filename
    print 'Reading from DB %s' % db_loc
    db = SqliteDatabase(db_loc)

    thermo = estimators[args.thermodynamics_source]
    print "Using the thermodynamic estimations of: " + thermo.name
    
    kegg = Kegg.getInstance()
    thermo.bounds = deepcopy(kegg.cid2bounds)
    
    dirname = os.path.dirname(output_filename)
    if not os.path.exists(dirname):
        print 'Making output directory %s' % dirname
        _mkdir(dirname)
    
    print 'Executing thermodynamic pathway analysis'
    html_writer = HtmlWriter(output_filename)
    thermo_analyze = ThermodynamicAnalysis(db, html_writer, thermodynamics=thermo)
    thermo_analyze.analyze_pathway(input_filename)

    
Exemplo n.º 24
0
def main():
    db = database.SqliteDatabase('../res/gibbs.sqlite')
    html_writer = HtmlWriter("../res/nist/report.html")
    gc = GroupContribution(db)
    gc.override_gc_with_measurements = True
    gc.init()
    grad = GradientAscent(gc)
    nist = Nist(db, html_writer, gc.kegg())
    nist.FromDatabase()
    alberty = Alberty()
    hatzi = Hatzi()

    if True:
        grad.load_nist_data(nist,
                            alberty,
                            skip_missing_reactions=False,
                            T_range=(298, 314))
        grad.verify_results("Alberty", alberty, html_writer)

        #grad.write_pseudoisomers("../res/nist/nist_dG0_f.csv")

        #html_writer.write("<h2>Using Group Contribution (Hatzimanikatis' implementation)</h2>")
        #html_writer.write("<h3>Correlation with the reduced NIST database (containing only compounds that appear in Alberty's list)</h3>")
        #logging.info("calculate the correlation between Hatzimanikatis' predictions and the reduced NIST database")
        #grad.verify_results("Hatzimanikatis_Reduced", hatzi, html_writer)

        #grad.load_nist_data(nist, hatzi, skip_missing_reactions=True, T_range=(298, 314))
        grad.verify_results("Hatzimanikatis", hatzi, html_writer)

        #grad.load_nist_data(nist, gc, skip_missing_reactions=True, T_range=(298, 314))
        grad.verify_results("Milo", gc, html_writer)
    elif False:
        # Run the gradient ascent algorithm, where the starting point is the same file used for training the GC algorithm
        grad.load_dG0_data("../data/thermodynamics/dG0.csv")
        # load the data for the anchors (i.e. compounds whose dG0 should not be changed - usually their value will be 0).
        grad.anchors = grad.load_dG0_data(
            "../data/thermodynamics/nist_anchors.csv")
        grad.load_nist_data(nist, grad, skip_missing_reactions=True)
        print "Training %d compounds using %d reactions: " % (len(
            grad.cid2pmap_dict.keys()), len(grad.data))
        grad.hill_climb(max_i=20000)
        grad.save_energies(grad.gc.comm, "gradient_cid2prm")
        grad.verify_results("gradient1")

    elif False:
        # Run the gradient ascent algorithm, where the starting point is Alberty's table from (Mathematica 2006)
        grad.load_nist_data(nist, alberty, skip_missing_reactions=True)
        print "Training %d compounds using %d reactions: " % (len(
            grad.cid2pmap_dict.keys()), len(grad.data))
        grad.cid2pmap_dict = alberty.cid2pmap_dict
        grad.hill_climb(max_i=20000)
        grad.save_energies(grad.gc.comm, "gradient_cid2prm")
        grad.verify_results("gradient2")

    elif False:
        # Run the gradient ascent algorithm, where the starting point is Alberty's table from (Mathematica 2006)
        # Use DETERMINISTIC gradient ascent
        grad.load_nist_data(nist,
                            alberty,
                            skip_missing_reactions=True,
                            T_range=(24 + 273.15, 40 + 273.15))
        print "Training %d compounds using %d reactions: " % (len(
            grad.cid2pmap_dict.keys()), len(grad.data))
        grad.cid2pmap_dict = alberty.cid2pmap_dict
        grad.deterministic_hill_climb(max_i=200)
        grad.save_energies(grad.gc.comm, "gradient_cid2prm")
        grad.verify_results("gradient_deterministic")

    elif False:
        # Run the gradient ascent algorithm, where the starting point arbitrary (predict all of the NIST compounds)
        grad = GradientAscent(gc)
        grad.load_nist_data(nist, skip_missing_reactions=False)
        print "Training %d compounds using %d reactions: " % (len(
            grad.cid2pmap_dict.keys()), len(grad.data))
        grad.hill_climb(max_i=20000)
        grad.save_energies(grad.gc.comm, "gradient_cid2prm")
        grad.verify_results("gradient3")

    elif False:  # Use Alberty's table from (Mathematica 2006) to calculate the dG0 of all possible reactions in KEGG
        grad = GradientAscent(gc)
        grad.cid2pmap_dict = alberty.cid2pmap_dict
        (pH, I, T) = (7, 0, 300)
        counter = 0
        for rid in grad.kegg.get_all_rids():
            sparse_reaction = grad.kegg.rid2sparse_reaction(rid)
            try:
                dG0 = grad.reaction_to_dG0(sparse_reaction, pH, I, T)
                print "R%05d: dG0_r = %.2f [kJ/mol]" % (rid, dG0)
                counter += 1
            except MissingCompoundFormationEnergy as e:
                #print "R%05d: missing formation energy of C%05d" % (rid, e.cid)
                pass
        print "Managed to calculate the dG0 of %d reactions" % counter

    elif False:
        util._mkdir("../res/nist/fig")
        csv_writer = csv.writer(open("../res/nist/pseudoisomers.csv", "w"))

        cid_set = set()
        for row in nist.data:
            sparce_reaction = row['sparse']
            cid_set.update(sparce_reaction.keys())

        html_writer.write("<table border=1>\n")
        for cid in sorted(list(cid_set)):
            html_writer.write("  <tr><td>C%05d</td><td>%s</td><td>" %
                              (cid, grad.kegg.cid2name(cid)))
            try:
                mol = grad.kegg.cid2mol(cid)
                img_fname = '../res/nist/fig/C%05d.png' % cid
                html_writer.embed_img(img_fname, "C%05d" % cid)
                mol.draw(show=False, filename=img_fname)
            except AssertionError as e:
                html_writer.write("WARNING: cannot draw C%05d - %s" %
                                  (cid, str(e)))
            except KeggParseException as e:
                html_writer.write("WARNING: cannot draw C%05d - %s" %
                                  (cid, str(e)))
            html_writer.write("</td><td>")
            if (cid in alberty.cid2pmap_dict):
                for (nH, z) in alberty.cid2pmap_dict[cid].keys():
                    html_writer.write("(nH=%d, z=%d)<br>" % (nH, z))
                    csv_writer.writerow((cid, nH, z))
            else:
                nH = grad.kegg.cid2num_hydrogens(cid)
                z = grad.kegg.cid2charge(cid)
                html_writer.write("unknown pseudoisomers<br>")
                html_writer.write("(nH=%d, z=%d)" % (nH, z))
                csv_writer.writerow((cid, nH, z))

            html_writer.write("</td></tr>\n")
        html_writer.write("</table>\n")
    html_writer.close()
Exemplo n.º 25
0
def AnalyzeConcentrationGradient(pathway_file,
                                 output_prefix,
                                 thermo,
                                 conc_range,
                                 cids=[],
                                 pH=None):
    compound_names = ','.join([thermo.kegg.cid2name(cid) for cid in cids])
    pathway_list = KeggFile2PathwayList(pathway_file)
    pathway_names = [entry for (entry, _) in pathway_list]
    html_writer = HtmlWriter('%s.html' % output_prefix)

    # run once just to make sure that the pathways are all working:
    logging.info("testing all pathways with default concentrations")
    data = GetAllOBDs(pathway_list,
                      html_writer,
                      thermo,
                      pH=pH,
                      section_prefix="test",
                      balance_water=True,
                      override_bounds={})

    csv_output = csv.writer(open('%s.csv' % output_prefix, 'w'))
    csv_output.writerow(['pH', '[' + compound_names + ']'] + pathway_names)

    conc_vec = 10**(-ParseConcentrationRange(conc_range)
                    )  # logarithmic scale between 10mM and 1nM
    override_bounds = {}

    obd_mat = []
    for conc in conc_vec.flat:
        for cid in cids:
            override_bounds[cid] = (conc, conc)
        logging.info("[%s] = %.1e M" % (compound_names, conc))
        data = GetAllOBDs(pathway_list,
                          html_writer=None,
                          thermo=thermo,
                          pH=pH,
                          section_prefix="",
                          balance_water=True,
                          override_bounds=override_bounds)
        obds = [d['OBD'] for d in data]
        obd_mat.append(obds)
        csv_output.writerow([data[0]['pH'], conc] + obds)
    obd_mat = np.matrix(
        obd_mat)  # rows are pathways and columns are concentrations

    fig = plt.figure(figsize=(6, 6), dpi=90)
    colormap = color.ColorMap(pathway_names)
    for i, name in enumerate(pathway_names):
        plt.plot(conc_vec,
                 obd_mat[:, i],
                 '-',
                 color=colormap[name],
                 figure=fig)
    plt.title("OBD vs. [%s]" % (compound_names), figure=fig)
    plt.xscale('log')
    plt.ylim(ymin=0)
    plt.xlabel('[%s] (in M)' % compound_names, figure=fig)
    plt.ylabel('Optimized Distributed Bottleneck [kJ/mol]', figure=fig)
    plt.legend(pathway_names)
    html_writer.write('<h2>Summary figure</h1>\n')
    html_writer.embed_matplotlib_figure(fig)
    html_writer.close()
Exemplo n.º 26
0
if __name__ == "__main__":
    kegg = Kegg.getInstance()
    
    
    graph = {}
    for rid in kegg.get_all_rids():
        r = kegg.rid2reaction(rid)
        for cid1 in r.sparse.keys():
            for cid2 in r.sparse.keys():
                if r.sparse[cid1] * r.sparse[cid2] < 0:
                    graph.setdefault(cid1, set()).add(cid2)
    
    queue = [355]
    cofactors = set([1,2,3,4,5,6,7,8,9,10,11,13,14,20,28,30])
    html_writer = HtmlWriter('../res/kegg_bfs.html')
    
    for i in xrange(3):
        next_queue = set()
        cofactors.update(queue)
        while queue:
            cid = queue.pop(0)
            next_queue.update(graph[cid])
        queue = list(next_queue.difference(cofactors))
        
        for cid in queue:
            try:
                html_writer.write(kegg.cid2mol(cid).ToSVG())
                html_writer.write(kegg.cid2name(cid))
            except (KeggParseException, OpenBabelError):
                html_writer.write(kegg.cid2name(cid))
Exemplo n.º 27
0
    def WriteUniqueReactionReport(self, unique_sparse_reactions,
                                  unique_nist_row_representatives,
                                  unique_data_mat, full_data_mat,
                                  cid2nH_nMg=None):
        
        total_std = full_data_mat[2:4, :].std(1)
        
        fig = plt.figure()
        plt.plot(unique_data_mat[2, :].T, unique_data_mat[3, :].T, '.')
        plt.xlabel("$\sigma(\Delta_r G^\circ)$")
        plt.ylabel("$\sigma(\Delta_r G^{\'\circ})$")
        plt.title('$\sigma_{total}(\Delta_r G^\circ) = %.1f$ kJ/mol, '
                    '$\sigma_{total}(\Delta_r G^{\'\circ}) = %.1f$ kJ/mol' % 
                    (total_std[0, 0], total_std[1, 0]))
        self.html_writer.embed_matplotlib_figure(fig, width=640, height=480)
        logging.info('std(dG0_r) = %.1f' % total_std[0, 0])
        logging.info('std(dG\'0_r) = %.1f' % total_std[1, 0])
        
        rowdicts = []
        for i, reaction in enumerate(unique_sparse_reactions):
            logging.debug('Analyzing unique reaction: ' + 
                          str(unique_sparse_reactions[i]))
            ddG0 = self.GetDissociation().ReverseTransformReaction(reaction,
                pH=7, I=0.1, pMg=10, T=298.15, cid2nH_nMg=cid2nH_nMg)
            
            d = {}
            d["_reaction"] = reaction.to_hypertext(show_cids=False)
            d["reaction"] = reaction.FullReactionString(show_cids=False) # no hypertext for the CSV output
            d["Reference ID"] = unique_nist_row_representatives[i].ref_id
            d["EC"] = unique_nist_row_representatives[i].ec
            d["E(" + symbol_dr_G0 + ")"] = unique_data_mat[0, i]
            d["E(" + symbol_dr_G0_prime + ")"] = unique_data_mat[1, i]
            d["E(" + symbol_dr_G0 + ")'"] = unique_data_mat[0, i] + ddG0
            d["std(" + symbol_dr_G0 + ")"] = unique_data_mat[2, i]
            d["std(" + symbol_dr_G0_prime + ")"] = unique_data_mat[3, i]
            d["diff"] = unique_data_mat[2, i] - unique_data_mat[3, i]
            d["#observations"] = "%d" % unique_data_mat[4, i]
            
            flag = 0
            c_nad = reaction.sparse.get(3, 0)
            c_nadh = reaction.sparse.get(4, 0)
            c_nadp = reaction.sparse.get(6, 0)
            c_nadph = reaction.sparse.get(5, 0)
            if  c_nad == 1 and c_nadh == -1:
                flag = 1
            elif c_nad == -1 and c_nadh == 1:
                flag = -1
            elif c_nadp == 1 and c_nadph == -1:
                flag = 2
            elif c_nadp == -1 and c_nadph == 1:
                flag = -2
            d["Arren Flag"] = flag

            if d["diff"] > self.std_diff_threshold:
                _mkdir('../res/prc_reactions')
                link = "prc_reactions/%s.html" % reaction.name
                d["analysis"] = '<a href="%s">link</a>' % link
                reaction_html_writer = HtmlWriter(os.path.join('../res', link))
                self.AnalyzeSingleReaction(reaction,
                                           html_writer=reaction_html_writer)
            rowdicts.append(d)
        
        result_headers = ["E(" + symbol_dr_G0 + ")",
                          "E(" + symbol_dr_G0_prime + ")", 
                          "E(" + symbol_dr_G0 + ")'",
                          "std(" + symbol_dr_G0 + ")",
                          "std(" + symbol_dr_G0_prime + ")"]
        rowdicts.sort(key=lambda x:x["diff"], reverse=True)
        self.html_writer.write_table(rowdicts, ["reaction", "Reference ID"] + 
                                     result_headers + ["EC", "#observations", "analysis"],
                                     decimal=1)
        csv_writer = csv.DictWriter(open('../res/nist_regression_unique.csv', 'w'),
                                    ["_reaction", "Reference ID", "EC", "#observations"]
                                    + result_headers + ['Arren Flag'],
                                    extrasaction='ignore')
        csv_writer.writeheader()
        csv_writer.writerows(rowdicts)
Exemplo n.º 28
0
def main():
    html_writer = HtmlWriter("../res/nist/report.html")
    estimators = LoadAllEstimators()
    nist = Nist()
    nist.T_range = (273.15 + 24, 273.15 + 40)
    #nist.override_I = 0.25
    #nist.override_pMg = 14.0
    #nist.override_T = 298.15

    html_writer.write('<p>\n')
    html_writer.write("Total number of reaction in NIST: %d</br>\n" %
                      len(nist.data))
    html_writer.write("Total number of reaction in range %.1fK < T < %.1fK: %d</br>\n" % \
                      (nist.T_range[0], nist.T_range[1], len(nist.SelectRowsFromNist())))
    html_writer.write('</p>\n')

    reactions = {}
    reactions['KEGG'] = []
    for reaction in Kegg.getInstance().AllReactions():
        try:
            reaction.Balance(balance_water=True, exception_if_unknown=True)
            reactions['KEGG'].append(reaction)
        except (KeggReactionNotBalancedException, KeggParseException,
                OpenBabelError):
            pass

    reactions['FEIST'] = Feist.FromFiles().reactions
    reactions['NIST'] = nist.GetUniqueReactionSet()

    pairs = []
    #pairs += [('hatzi_gc', 'UGC')], ('PGC', 'PRC'), ('alberty', 'PRC')]
    for t1, t2 in pairs:
        logging.info('Writing the NIST report for %s vs. %s' %
                     (estimators[t1].name, estimators[t2].name))
        html_writer.write('<p><b>%s vs. %s</b> ' %
                          (estimators[t1].name, estimators[t2].name))
        html_writer.insert_toggle(start_here=True)
        two_way_comparison(html_writer=html_writer,
                           thermo1=estimators[t1],
                           thermo2=estimators[t2],
                           reaction_list=reactions['FEIST'],
                           name='%s_vs_%s' % (t1, t2))
        html_writer.div_end()
        html_writer.write('</p>')

    if False:
        estimators['alberty'].CompareOverKegg(
            html_writer,
            other=estimators['PRC'],
            fig_name='kegg_compare_alberty_vs_nist')

    rowdicts = []
    rowdict = {'Method': 'Total'}
    for db_name, reaction_list in reactions.iteritems():
        rowdict[db_name + ' coverage'] = len(reaction_list)
    rowdicts.append(rowdict)

    for name in ['UGC', 'PGC', 'PRC', 'alberty', 'merged', 'hatzi_gc']:
        thermo = estimators[name]
        logging.info('Writing the NIST report for %s' % thermo.name)
        html_writer.write('<p><b>%s</b> ' % thermo.name)
        html_writer.insert_toggle(start_here=True)
        num_estimations, rmse = nist.verify_results(html_writer=html_writer,
                                                    thermodynamics=thermo,
                                                    name=name)
        html_writer.div_end()
        html_writer.write('N = %d, RMSE = %.1f</p>\n' %
                          (num_estimations, rmse))
        logging.info('N = %d, RMSE = %.1f' % (num_estimations, rmse))

        rowdict = {
            'Method': thermo.name,
            'RMSE (kJ/mol)': "%.1f (N=%d)" % (rmse, num_estimations)
        }
        for db_name, reaction_list in reactions.iteritems():
            n_covered = thermo.CalculateCoverage(reaction_list)
            percent = n_covered * 100.0 / len(reaction_list)
            rowdict[db_name +
                    " coverage"] = "%.1f%% (%d)" % (percent, n_covered)
            logging.info(db_name + " coverage = %.1f%%" % percent)
        rowdicts.append(rowdict)

    headers = ['Method', 'RMSE (kJ/mol)'] + \
        [db_name + ' coverage' for db_name in reactions.keys()]
    html_writer.write_table(rowdicts, headers=headers)
Exemplo n.º 29
0
def AnalyzePHGradient(pathway_file, output_prefix, thermo, conc_range):
    pathway_list = KeggFile2PathwayList(pathway_file)
    pathway_names = [entry for (entry, _) in pathway_list]
    html_writer = HtmlWriter('%s.html' % output_prefix)

    # run once just to make sure that the pathways are all working:
    logging.info("testing all pathways with default pH")
    data = GetAllOBDs(pathway_list,
                      html_writer,
                      thermo,
                      pH=None,
                      section_prefix="test",
                      balance_water=True,
                      override_bounds={})

    csv_output = csv.writer(open('%s.csv' % output_prefix, 'w'))
    csv_output.writerow(['pH'] + pathway_names)

    util._mkdir(output_prefix)
    shadow_csvs = {}
    for d in data:
        path = '%s/%s.csv' % (output_prefix, d['entry'])
        shadow_csvs[d['entry']] = csv.writer(open(path, 'w'))
        shadow_csvs[d['entry']].writerow(['pH'] + d['rids'])

    pH_vec = ParseConcentrationRange(conc_range)
    obd_mat = []
    for pH in pH_vec.flat:
        logging.info("pH = %.1f" % (pH))
        data = GetAllOBDs(pathway_list,
                          html_writer=None,
                          thermo=thermo,
                          pH=pH,
                          section_prefix="",
                          balance_water=True,
                          override_bounds={})
        obds = [d['OBD'] for d in data]
        obd_mat.append(obds)
        csv_output.writerow([data[0]['pH']] + obds)

        for d in data:
            if type(d['reaction prices']) != types.FloatType:
                prices = list(d['reaction prices'].flat)
                shadow_csvs[d['entry']].writerow([pH] + prices)

    obd_mat = np.matrix(
        obd_mat)  # rows are pathways and columns are concentrations

    fig = plt.figure(figsize=(6, 6), dpi=90)
    colormap = color.ColorMap(pathway_names)
    for i, name in enumerate(pathway_names):
        plt.plot(pH_vec, obd_mat[:, i], '-', color=colormap[name], figure=fig)
    plt.title("OBD vs. pH", figure=fig)
    plt.ylim(0, np.max(obd_mat.flat))
    plt.xlabel('pH', figure=fig)
    plt.ylabel('Optimized Distributed Bottleneck [kJ/mol]', figure=fig)
    plt.legend(pathway_names)
    html_writer.write('<h2>Summary figure</h1>\n')
    html_writer.embed_matplotlib_figure(fig)

    html_writer.close()
                        '--leave_one_out',
                        action='store_true',
                        default=False,
                        help='A flag for running the Leave One Out analysis')
    return parser


if __name__ == "__main__":
    logger = logging.getLogger('')
    logger.setLevel(logging.DEBUG)

    parser = MakeOpts()
    args = parser.parse_args()
    util._mkdir('../res')
    db = SqliteDatabase('../res/gibbs.sqlite', 'w')
    html_writer = HtmlWriter('../res/ugc.html')

    ugc = UnifiedGroupContribution(db,
                                   html_writer,
                                   anchor_all=args.anchor_all_formations)
    ugc.LoadGroups(FromDatabase=(not args.recalc_groups))
    ugc.LoadObservations(FromDatabase=(not args.recalc_observations))
    ugc.LoadGroupVectors(FromDatabase=(not args.recalc_groupvectors))
    ugc.LoadData(FromDatabase=(not args.recalc_matrices))

    if args.dump:
        ugc.SaveDataToMatfile()
        sys.exit(0)
    if args.train:
        ugc.EstimateKeggCids()
        sys.exit(0)