def __init__(self, modules_file, experiment_name, max_module_size=6): self.modules_file = modules_file self.experiment_name = experiment_name self.max_module_size = max_module_size util._mkdir("../log") self.logfile = open( "../log/pathologic_" + self.experiment_name + ".log", "w") util._mkdir("../results") util._mkdir("../results/pathologic_" + self.experiment_name) self.html_writer = HtmlWriter("../results/pathologic_" + self.experiment_name + ".html") self.html_writer.write( "<h1>List of optimal and non-optimal pathways</h1>\n") self.html_writer.write("<ul>\n") self.line_counter = 0 self.pathfinder = None
def __init__(self, modules_file, experiment_name, max_module_size=6): self.modules_file = modules_file self.experiment_name = experiment_name self.max_module_size = max_module_size util._mkdir("../log") self.logfile = open("../log/pathologic_" + self.experiment_name + ".log", "w") util._mkdir("../results") util._mkdir("../results/pathologic_" + self.experiment_name) self.html_writer = HtmlWriter("../results/pathologic_" + self.experiment_name + ".html") self.html_writer.write("<h1>List of optimal and non-optimal pathways</h1>\n") self.html_writer.write("<ul>\n") self.line_counter = 0 self.pathfinder = None
def main(): main_html = HtmlWriter('res/fba.html') main_html.write('<h1>Flux Balance Analysis</h1>\n') carbon_sources = {} BM_lower_bound = 0.01 ko_reactions = '' ki_reactions = '' PPP_reaction = '' # full model carbon sources: glc, fru, xyl__D, succ, ac, rib__D, pyr ######################################### # Core model for testing glycolysis KOs # ######################################### #model = init_wt_model('core', {'ac' : -10}); ko_reactions = 'PGM'; ki_reactions = 'RED'; #model = init_wt_model('core', {'glc' : -10}); ko_reactions = 'PFK'; ki_reactions = 'RED'; ####################################### # Full model Rubisco optimization KOs # ####################################### #model = init_wt_model('full', {'ac' : -10}); ko_reactions = 'PGM,TRSARr,HPYRRx,HPYRRy'; ki_reactions = 'RED'; #model = init_wt_model('full', {'rib_D' : -10}); ko_reactions = 'TKT1'; ki_reactions = 'RBC,PRK'; PPP_reaction = 'RBC'; model = init_wt_model('full', {'xyl_D': -10}) ko_reactions = 'RPI' ki_reactions = 'RBC,PRK' PPP_reaction = 'RBC' #model = init_wt_model('full', {'xyl_D' : -10}); ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA'; ki_reactions = 'RBC,PRK'; #model = init_wt_model('full', {'fru' : -10, 'rib_D' : -10}); ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA,TKT1,TKT2'; ki_reactions = 'PKT'; ############################### # Shikimate generating strain # ############################### #model = init_wt_model('full', {'fru' : -10}); #ko_reactions = 'G6PDH2r,TALA'; ki_reactions = 'EX_3dhsk_c'; PPP_reaction = 'EX_3dhsk_c'; #ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA'; ki_reactions = 'PKT'; PPP_reaction = 'PKT'; ########################################################## # Testing no growth when electrons are provided directly # ########################################################## #model = init_wt_model('full', {}); ki_reactions = 'RED'; #ko_reactions = "POR5,MCITL2"; #ko_reactions = "POR5,FTHFLi,GART,RPI"; models = {'WT': model} if ko_reactions: for k in models.keys(): m = deepcopy(models[k]) knockout_reactions(m, ko_reactions) models[k + ' -%s' % ko_reactions] = m if ki_reactions: for k in models.keys(): m = deepcopy(models[k]) knockin_reactions(m, ki_reactions) models[k + ' +%s' % ki_reactions] = m # Run the optimization for the objective reaction and medium composition # set in the file. main_html.write('<table border="1">\n') main_html.write( '<tr><td><b>Model Name</b></td><td><b>Growth Yield</b></td></tr>\n') growths = {} for name, model in sorted(models.iteritems()): print "solving %50s model" % name, ok = OptKnock(model) ok.prepare_FBA_primal() ok.solve() growths[name] = ok.get_objective_value() if growths[name] is None: main_html.write('<tr><td>%s</td><td>infeasible</td></tr>\n' % name) else: print ': f = %.3g' % growths[name] main_html.write('<tr><td>') html = main_html.branch(name) main_html.write('</td><td>%.3g</td></tr>\n' % growths[name]) html.write('<h1>Model name: %s</h1>\n' % name) html.write('<h2>Growth Yield: %.3g</h2>\n' % growths[name]) ok.draw_svg(html) ok.model_summary(html) main_html.write('</table>\n') if PPP_reaction: print 'Calculating Phenotypic Phase Plane for phosphoketolase ...' fig, ax = plt.subplots(1, figsize=(6, 6)) plot_multi_PPP(models, PPP_reaction, ax) ax.set_title('Phenotypic Phase Plane') main_html.embed_matplotlib_figure(fig, width=400, height=400)
def main(): Pentose_target_compounds = [ 'D-Xylulose-5P', 'D-Ribulose-5P', 'D-Ribose-5P' ] PP_compounds = \ ['D-Xylulose-5P',\ 'D-Ribulose-5P',\ 'D-Ribose-5P',\ 'D-Erythrose-4P',\ 'D-Sedoheptulose-7P',\ 'D-Fructose-6P',\ 'D-Glyceraldehyde-3P'] Glycolysis_compounds = \ ['Dihydroxyacetone-3P',\ 'D-Glyceraldehyde-3P',\ 'Bisphosphoglycerate',\ '3-Phosphoglycerate',\ '2-Phosphoglycerate',\ 'Phosphoenolpyruvate',\ 'Pyruvate'] TCA_compounds = \ ['Oxaloacetate',\ 'Citrate',\ 'cis-Aconitate',\ 'D-Isocitrate',\ '2-Ketoglutarate',\ #succinyl-CoA\ 'Succinate',\ 'Fumarate',\ 'Malate',\ ] Biosynthese_compounds = PP_compounds + Glycolysis_compounds + TCA_compounds pathway_list = [] # fast test pathway_list.append( ("TEST", ['2-Phosphoglycerate'], ['Bisphosphoglycerate'], None)) # Optimality Modules: pathway_list.append( ("Glucose to Fructose", ['D-glucose-6P'], ['D-fructose-6P'], None)) pathway_list.append( ("Fructose to Glucose", ['D-fructose-6P'], ['D-glucose-6P'], None)) pathway_list.append(("oxaloacetate+acetyl-CoA to citrate", ['oxaloacetate + acetyl-CoA'], ['citrate'], None)) pathway_list.append( ("cis-aconitate to succinate", ['cis-aconitate'], ['succinate'], None)) pathway_list.append( ("D-xylose to D-xylulose-5P", ['D-Xylose'], ['D-Xylulose-5P'], None)) pathway_list.append(("D-arabitol to D-xylulose-5P", ['D-Arabitol'], ['D-Xylulose-5P'], None)) pathway_list.append(("L-arabinose to D-xylulose-5P", ['L-Arabinose'], ['D-Xylulose-5P'], None)) pathway_list.append(("L-xylulose to D-xylulose-5P", ['L-Xylulose'], ['D-Xylulose-5P'], None)) pathway_list.append( ("ribitol to D-xylulose-5P", ['Ribitol'], ['D-Xylulose-5P'], None)) pathway_list.append( ("D-ribose to D-xylulose-5P", ['D-Ribose'], ['D-Xylulose-5P'], None)) pathway_list.append(("Oxaloacetate to 2-Ketoglutarate", ['Oxaloacetate'], ['2-Ketoglutarate'], None)) pathway_list.append( ("Citrate to 2-Ketoglutarate", ['Citrate'], ['2-Ketoglutarate'], None)) pathway_list.append( ("Pentose Phosphate", ['D-Xylulose-5P + D-Xylulose-5P + D-Ribose-5P'], ['D-Fructose-6P + D-Fructose-6P + D-Glyceraldehyde-3P'], None)) #pathway_list.append(("Pentose Phosphate", ['D-Xylulose-5P + D-Ribose-5P'], ['D-Glyceraldehyde-3P + D-Sedoheptulose-7P'], None)) pathway_list.append( ("D-glucose to D-ribulose-5P", ['D-Glucose'], ['D-Ribulose-5P'], None)) pathway_list.append(("D-glucose to D-fructose-16P", ['D-Glucose'], ['D-Fructose-16P'], None)) pathway_list.append(("D-fructose-6P to GAP+DHAP", ['D-Fructose-6P'], ['D-Glyceraldehyde-3P + Dihydroxyacetone-3P'], None)) pathway_list.append( ("GAP to 3-PG", ['D-Glyceraldehyde-3P'], ['3-Phosphoglycerate'], None)) pathway_list.append( ("GAP to 2-PG", ['D-Glyceraldehyde-3P'], ['2-Phosphoglycerate'], None)) pathway_list.append( ("BPG to 3-PG", ['Bisphosphoglycerate'], ['3-Phosphoglycerate'], None)) pathway_list.append( ("BPG to 2-PG", ['Bisphosphoglycerate'], ['2-Phosphoglycerate'], None)) pathway_list.append( ("BPG to PEP", ['Bisphosphoglycerate'], ['Phosphoenolpyruvate'], None)) pathway_list.append( ("3-PG to PYR", ['3-Phosphoglycerate'], ['Pyruvate'], None)) # Biosynthesis pathway_list.append( ("3-PG to L-Serine", ['3-Phosphoglycerate'], ['L-Serine'], None)) pathway_list.append( ("L-Serine to Glycine", ['L-Serine'], ['Glycine'], None)) pathway_list.append( ("Pyruvate to L-Alanine", ['Pyruvate'], ['L-Alanine'], None)) pathway_list.append( ("Synthesis of L-Serine", Biosynthese_compounds, ['L-Serine'], None)) pathway_list.append( ("Synthesis of L-Alanine", Biosynthese_compounds, ['L-Alanine'], None)) pathway_list.append( ("Synthesis of Glycine", Biosynthese_compounds, ['Glycine'], None)) pathway_list.append(("Synthesis of L-Aspartate", Biosynthese_compounds, ['L-Aspartate'], None)) pathway_list.append(("Synthesis of L-Glutamate", Biosynthese_compounds, ['L-Glutamate'], None)) # Pentose utilization pathway_list.append(("L-Arabinose to Pentose Phosphate", ['L-Arabinose'], Pentose_target_compounds, None)) pathway_list.append(("D-Xylose to Pentose Phosphate", ['D-Xylose'], Pentose_target_compounds, None)) pathway_list.append(("D-Ribose to Pentose Phosphate", ['D-Ribose'], Pentose_target_compounds, None)) pathway_list.append(("Ribitol to Pentose Phosphate", ['Ribitol'], Pentose_target_compounds, None)) pathway_list.append(("D-Arabitol to Pentose Phosphate", ['D-Arabitol'], Pentose_target_compounds, None)) # Glycolysis pathway_list.append( ("GAP to PYR", ['D-Glyceraldehyde-3P'], ['Pyruvate'], 'PP')) pathway_list.append(("GAP to DHAP", ['D-Glyceraldehyde-3P'], ['Dihydroxyacetone-3P'], 'PP')) pathway_list.append(("GAP to PEP", ['D-Glyceraldehyde-3P + H2O'], ['Phosphoenolpyruvate + H2O'], 'PP')) pathway_list.append( ("GAP to 2-PG", ['D-Glyceraldehyde-3P'], ['2-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC to GAP", ['D-Glucose'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append( ("GLC to PYR", ['Glucose'], ['Pyruvate + Pyruvate'], 'PP')) pathway_list.append(("GLC-36P to GAP", ['D-Glucose-36P'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append(("GLC-6P to GAP", ['D-Glucose-6P'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append(("GLC-6P to BPG", ['D-Glucose-6P'], ['Bisphosphoglycerate + Bisphosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to 3-PG", ['D-Glucose-6P'], ['3-Phosphoglycerate + 3-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to 2-PG", ['D-Glucose-6P'], ['2-Phosphoglycerate + 2-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to PEP", ['D-Glucose-6P'], ['Phosphoenolpyruvate + Phosphoenolpyruvate'], 'PP')) pathway_list.append( ("2-PG to PYR", ['2-Phosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append( ("3-PG to PYR", ['3-Phosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append( ("BPG to PYR", ['Bisphosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append( ("BPG to PEP", ['Bisphosphoglycerate'], ['Phosphoenolpyruvate'], 'PP')) # Arren's project pathway_list.append( ("Glyoxylate + GAP to Pentose", ['Glyoxylate + D-Glyceraldehyde-3P'], Pentose_target_compounds, None)) pathway_list.append( ("Glyoxylate + PYR to Pentose", ['Glyoxylate + Pyruvate'], Pentose_target_compounds, None)) pathway_list.append( ("Glycolate + GAP to Pentose", ['Glycolate + D-Glyceraldehyde-3P'], Pentose_target_compounds, None)) pathway_list.append( ("Glycolate + PYR to Pentose", ['Glycolate + Pyruvate'], Pentose_target_compounds, None)) pathway_names = [pathway[0] for pathway in pathway_list] pathway_map = {} for pathway in pathway_list: pathway_map[pathway[0]] = pathway[1:] if (len(sys.argv) > 1): pathway_name = pathway_names[int(sys.argv[1]) - 1] else: pathway_name = TkListSelection(pathway_names, "Choose a pathway:") if (pathway_name == None): sys.exit(0) (substrates, products, pruning_method) = pathway_map[pathway_name] pathfinder = PathFinder(carbon_only=False, pruning_method=pruning_method, ignore_chirality=True) print "-" * 80 + "\nChosen pathway name is %s\n" % pathway_name + "-" * 80 util._mkdir("../results") util._mkdir("../results/" + pathway_name) html_writer = HtmlWriter("../results/" + pathway_name + ".html") html_writer.write("<h1><center>%s</center></h1>\n" % pathway_name) html_writer.write("<ul>\n") for i in range(len(substrates)): for j in range(len(products)): ##(subs, prod) = pathfinder.balance_reaction(substrates[i], products[j]) (subs, prod) = (substrates[i], products[j]) pathway_prefix = "pathway_%d_%d" % (i, j) util._mkdir("../results/" + pathway_name + "/" + pathway_prefix) pathfinder.solve_pathway(subs, prod, html_writer, pathway_name, pathway_prefix, max_levels=6, stop_after_first_solution=True) html_writer.flush() html_writer.write("</ul>\n") html_writer.display() return
def make_welcome_page(self, mailaddr, filename): db = Database() try: prob = db.get_properties('maildata') user_name = prob[mailaddr] writer = HtmlWriter(open(filename, mode='w')) writer.title('Welcome to ' + user_name + 'is page!') writer.paragraph(user_name + 'のページへようこそ。') writer.paragraph('メール待っていますね。') writer.mailto(mailaddr, user_name) writer.close() print(filename + ' ' + 'is created for' + mailaddr + ' ' + '(' + user_name + ')') except IOError as e: logging.exception(e)
def make_welcome_page(mailaddr, filename): # try: # username = '******' # mailaddr = 'mailaddr' mailprop = Database.get_properties('maildata') # print mailprop username = mailprop.get('user', mailaddr) myfile = open(filename, 'w') writer = HtmlWriter(myfile) writer.title('Welcom to ' + username + ' s page!') writer.paragraph(username + 'のページへようこそ。') writer.paragraph('メールまっていますね。') writer.mailto(mailaddr, username) writer.closing() print filename + ' is created for ' + mailaddr + ' (' + username + ')'
#!/usr/bin/python import sys import os import util from chemconvert import hash2graph from html_writer import HtmlWriter from svg import Scene html = HtmlWriter("../results/hash_list.html") util._mkdir("../results/hash_list") for line in util.parse_text_file(sys.argv[1]): print line graph = hash2graph(line) graph.initialize_pos() scene = graph.svg(Scene(200, 200, font_size=12)) html.write_svg(scene, "../results/hash_list/" + line) html.display()
def write_recipients_page(html_dir, recipients_filename, funder1, funder2, recipients): html_fp = open(os.path.join(html_dir,recipients_filename), 'w') html_writer = HtmlWriter(html_fp) html_writer.open_tag('html') html_writer.open_tag('head') html_writer.empty_tag('link', {'href': 'style.css', 'rel':'stylesheet'}) html_writer.empty_tag('link', {'href': 'overlap.css', 'rel':'stylesheet'}) html_writer.close_tag('head') html_writer.open_tag('body') html_writer.open_tag('div', {'class': 'container'}) html_writer.write_html('h1', 'Recipients common to {0} and {1}'.format(funder1, funder2)) html_writer.open_tag('ul') for recipient in recipients: html_writer.write_html('li', recipient) html_writer.close_tag('ul') html_writer.close_tag('div') html_writer.close_tag('body') html_writer.close_tag('html') html_fp.close()
class Pathologic: def __init__(self, modules_file, experiment_name, max_module_size=6): self.modules_file = modules_file self.experiment_name = experiment_name self.max_module_size = max_module_size util._mkdir("../log") self.logfile = open("../log/pathologic_" + self.experiment_name + ".log", "w") util._mkdir("../results") util._mkdir("../results/pathologic_" + self.experiment_name) self.html_writer = HtmlWriter("../results/pathologic_" + self.experiment_name + ".html") self.html_writer.write("<h1>List of optimal and non-optimal pathways</h1>\n") self.html_writer.write("<ul>\n") self.line_counter = 0 self.pathfinder = None def find_shortest_pathways(self, substrate, product, max_levels, stop_after_first_solution=True): G_subs = compound2graph(substrate) G_prod = compound2graph(product) return self.pathfinder.find_shortest_pathway([G_subs], [G_prod], max_levels=max_levels, stop_after_first_solution=stop_after_first_solution) def get_distance(self, substrate, product, max_levels): G_subs = compound2graph(substrate) G_prod = compound2graph(product) return self.pathfinder.find_distance([G_subs], [G_prod], max_levels=max_levels) def get_all_pathways(self, substrate, product, max_levels): """return all existing pathways with a length <= max_distance. """ (original_compound_map, possible_pathways, min_length) = self.find_shortest_pathways(substrate, product, max_levels=max_levels, stop_after_first_solution=False) if (possible_pathways == []): return [] else: scene_list = self.pathfinder.get_all_possible_scenes(original_compound_map, possible_pathways) return [scene for (cost, scene) in scene_list] # strip off the cost of each pathway def get_shortest_pathways(self, substrate, product, max_levels): """return -1 if the is no path with length <= max_levels. otherwise a pair containing a list of all pathways with the minimal length and the minimal length itself """ (original_compound_map, possible_pathways, min_length) = self.find_shortest_pathways(substrate, product, max_levels=max_levels, stop_after_first_solution=True) if (possible_pathways == []): return ([], -1) else: scene_list = self.pathfinder.get_all_possible_scenes(original_compound_map, possible_pathways) return ([scene for (cost, scene) in scene_list], min_length) # strip off the cost of each pathway def verify_pathway(self, pathway): sys.stdout.write("Verifying pathway: %s\n" % str(pathway)) for i in range(len(pathway)-1): sys.stdout.write(" - checking '%s' -> '%s' ... " % tuple(pathway[i:i+2])) sys.stdout.flush() distance = self.get_distance(pathway[i], pathway[i+1], 1) if (distance == -1): sys.stdout.write("FAILED (not neighbors)\n") else: sys.stdout.write("OK\n") sys.stdout.flush() def is_optimal(self, pathway, i, j, draw_scenes=False): sys.stdout.write(str(pathway[i:j+1]) + " ... ") wt_distance = j - i if (wt_distance <= 1): # we have verified that this is optimal already return True if (draw_scenes): # try to find at least one path which is shorter than the wild-type path: (scenes, dist) = self.get_shortest_pathways(pathway[i], pathway[j], wt_distance - 1) else: dist = self.get_distance(pathway[i], pathway[j], wt_distance - 1) if (dist == -1): # which means no shorter path has been found, hence the WT pathway is one of the shortest sys.stdout.write(" is optimal!\n") self.html_writer.write("<li><span style=color:green>%s - OPTIMAL</span></li>\n" % str(pathway[i:j+1])) self.html_writer.flush() return True else: # there is a shorter path than the WT one sys.stdout.write(" is not optimal!\n") self.html_writer.write("<li>\n <span style=color:red>%s - NOT OPTIMAL</span><br>\n " % str(pathway[i:j+1])) if (draw_scenes): #for s in scenes: s = scenes[0] # draws only the first scene (otherwise it could be too long) self.html_writer.write_svg(s, "pathologic_" + self.experiment_name + "/pathway_%d_%d_%d" % (self.line_counter, i, j)) self.html_writer.write("\n</li>\n") self.html_writer.flush() return False def find_modules(self, pathway, draw_scenes=False): self.verify_pathway(pathway) i = 0 for j in range(2, len(pathway)): if (j - i >= self.max_module_size): sys.stdout.write(str(pathway[i:(j+1)]) + " is too long for me, chopping off the head...\n") i += 1 # shorten the path from it's head until it is optimal (or too short, i.e. length=1) while ( (j - i) > 1 and (not self.is_optimal(pathway, i, j, draw_scenes=draw_scenes)) ): i += 1 def analyze(self, carbon_only=True, use_antimotifs=True, draw_scenes=False): for line in util.parse_text_file("../rec/" + self.modules_file + ".txt"): if (line[0] == '@'): line = line[1:] self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=False, use_antimotifs=use_antimotifs, outstream=self.logfile) else: self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=True, use_antimotifs=use_antimotifs, outstream=self.logfile) pathway = line.split(';') self.find_modules(pathway, draw_scenes=draw_scenes) self.line_counter += 1 def analyze_pairs(self, carbon_only=True, use_antimotifs=True, max_distance=4): distances = [] # the minimal pathway length between the substrate and the product alternatives = [] # each value is the number of alternative pathways with the minimal distance line_counter = 0 for line in util.parse_text_file("../rec/" + self.modules_file + ".txt"): if (line[0] == '@'): line = line[1:] self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=False, use_antimotifs=use_antimotifs, outstream=self.logfile) else: self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=True, use_antimotifs=use_antimotifs, outstream=self.logfile) (subs, prod, max_steps) = line.split(";", 2) if (max_steps in ['-1','inf','']): sys.stdout.write(subs + " -(?)-> " + prod) sys.stdout.flush() (scenes, dist) = self.get_shortest_pathways(subs, prod, max_distance) else: dist = int(max_steps) sys.stdout.write(subs + " -(%d)-> " % dist + prod) sys.stdout.flush() scenes = self.get_all_pathways(subs, prod, dist) if (dist == -1): sys.stdout.write(", Distance(L) = inf, N = 0\n") sys.stdout.flush() distances.append("inf") alternatives.append(0) self.html_writer.write("<li><span style=color:red>%s <-> %s (distance > %d)</span></li>\n" % (subs, prod, self.max_module_size)) self.html_writer.flush() else: sys.stdout.write(", Distance(L) = %d, N = %d\n" % (dist, len(scenes))) sys.stdout.flush() distances.append(dist) alternatives.append(len(scenes)) self.html_writer.write("<li><span style=color:green>%s <-> %s (distance = %d)</span></li>\n" % (subs, prod, dist)) for i in range(len(scenes)): self.html_writer.write("<li>") self.html_writer.write_svg(scenes[i], "pathologic_" + self.experiment_name + "/pair%d_path%d" % (line_counter,i)) self.html_writer.write("</li>\n") self.html_writer.flush() line_counter += 1 result_file = open("../results/" + self.experiment_name + ".txt", "w") result_file.write(str(distances) + "\n" + str(alternatives) + "\n") result_file.close() def display(self): self.html_writer.write("</ul>\n") self.html_writer.write(self.pathfinder.reactor.antimotif_summary()) self.html_writer.display() def __del__(self): del self.pathfinder self.logfile.close()
def main(core=True): main_html = HtmlWriter('res/optknock.html') main_html.write('<title>OptKnock</title>') main_html.write('<h1>OptKnock</h1>\n') if core: model = init_wt_model('core', {}, BM_lower_bound=0.1) knockin_reactions(model, 'EDD,EDA', 0, 1000) set_exchange_bounds(model, 'g6p', lower_bound=-10) main_html.write('<ul>\n') main_html.write('<li>Model used: E.coli core</li>\n') main_html.write( '<li>Carbon source: glucose-6P, v <= 10 [mmol/g(DW) h]</li>\n') main_html.write( '<li>Biomass yield lower bound: v >= 0.1 [mmol/g(DW) h]</li>\n') else: model = init_wt_model('full', {'rib_D': -10}, BM_lower_bound=0.1) main_html.write('<ul>\n') main_html.write('<li>Model used: iJO1366 (E. coli full model)</li>\n') main_html.write( '<li>Carbon source: D-ribose, v <= 10 [mmol/g(DW) h]</li>\n') main_html.write( '<li>Biomass yield lower bound: v >= 0.1 [mmol/g(DW) h]</li>\n') knockin_reactions(model, 'PRK,RBC', 0, 1000) main_html.write('<li>Added reactions: phosphoribulokinase, RuBisCo</li>\n') optknock_reaction = 'RBC' #knockin_reactions(model, 'DXS', 0, 1000) #main_html.write('<li>Added reactions: deoxyribose synthase</li>\n') #optknock_reaction = 'DXS' main_html.write('</ul>\n') print "Running standard FBA..." ok = OptKnock(model) ok.prepare_FBA_primal() ok.prob.writeLP('res/fba_primal.lp') ok.solve() ok.print_primal_results(short=True) print '-' * 50 print "Running dual FBA..." ok = OptKnock(model) ok.prepare_FBA_dual() ok.prob.writeLP('res/fba_dual.lp') ok.solve() ok.print_dual_results(short=True) print '-' * 50 if False: print "Running OptSlope..." ok = OptKnock(model) ok.prepare_optslope(optknock_reaction, num_deletions=3) ok.write_linear_problem('res/optslope.lp') solution = ok.solve() if solution.status is not None: ok.print_optknock_results(short=True) ok_model = ok.get_optknock_model() #fig, ax = plt.subplots(1) #plot_multi_PPP([model, ok_model], # ['Wild-Type', r'OptKnock'], # optknock_reaction, ax) #ax.set_title(title) #fig.savefig('res/OS_PPP.pdf') print '-' * 50 print "Running OptKnock for maximizing flux in %s..." % optknock_reaction ok = OptKnock(model) ok.prepare_optknock(optknock_reaction, num_deletions=1) ok.write_linear_problem('res/optknock.lp') solution = ok.solve() if solution.status is not None: ok.print_optknock_results(short=True) knockouts = ok.get_optknock_knockouts() ko_model = clone_model(model) knockout_reactions(ko_model, knockouts) main_html.write('<h2>Knockouts: %s</h2>\n' % knockouts) # draw the PPP as embedded SVG fig, ax = plt.subplots(1, figsize=(6, 6)) wt_PPP, wt_slope = get_PPP(model, optknock_reaction) ax.fill_between(wt_PPP[:, 0].flat, wt_PPP[:, 1].flat, wt_PPP[:, 2].flat, facecolor='#E0E0E0', linewidth=0) ko_PPP, slope = get_PPP(ko_model, optknock_reaction) if slope is None: ko_text = 'Not feasible at any Rubisco flux' ko_color = '#FF9073' else: slope = np.round(slope, 1) ko_text = ('Slope = %g' % slope) if slope > 0: ko_color = '#00B64F' else: ko_color = '#FF7060' ax.fill_between(ko_PPP[:, 0].flat, ko_PPP[:, 1].flat, ko_PPP[:, 2].flat, facecolor=ko_color, linewidth=1) main_html.embed_matplotlib_figure(fig, width=400, height=400) # draw the flux map as embedded SVG ok.draw_svg(main_html) # write the flux summary for the knockout model as HTML ok.model_summary(main_html)
def options_html(): """HTML options page. Shows bunch of options for conversion to HTML format. Converts to HTML using those options. """ if session.input_data_id is None: redirect(URL(index)) # get input_data = db.input_data(session.input_data_id) options = [] options += [(T('Page width') + ': ', INPUT(_type='number', _name='html_page_width', _style='width: 50px', _value=_optval('html_page_width', '800')) + ' ' + T('pixels'))] options += [(T('Image size') + ': ', INPUT(_type='number', _name='html_image_width', _style='width: 50px', _value=_optval('html_image_width', '300')) + ' x ' + INPUT(_type='number', _name='html_image_height', _style='width: 50px', _value=_optval('html_image_height', '300')) + ' ' + T('pixels'))] checked = _optval('html_image_upscale', '') == 'checked' options += [(T('Upscale images') + ': ', INPUT(_type='checkbox', _name='html_image_upscale', _value='checked', value=checked))] fmtoptions = [OPTION(T('31.12.2001'), _value='DMY.'), OPTION(T('31/12/2001'), _value='DMY/'), OPTION(T('2001-12-31'), _value='YMD-'), OPTION(T('12/31/2012'), _value='MDY/')] options += [(T('Date format') + ': ', SELECT(*fmtoptions, _name='datefmt', value=_optval('datefmt', 'DMY.'), _style='width: 150px'))] options += [('', INPUT(_value=T('Start'), _type='submit'))] form = FORM(TABLE(*[TR(*[TD(o) for o in opt]) for opt in options])) if form.process().accepted: # remember options session.options = form.vars # all config options config = ftp_config.Config() config['page_width'] = form.vars.html_page_width + 'px' config['image_width'] = form.vars.html_image_width + 'px' config['image_height'] = form.vars.html_image_height + 'px' config['image_upscale'] = form.vars.html_image_upscale == 'checked' config['date_format'] = form.vars.datefmt # convert it floc = FileLocator(os.path.join(request.folder, 'uploads', input_data.input_file)) reader = DrevoReader(floc) output = tempfile.TemporaryFile() writer = HtmlWriter(floc, output, config) writer.write(reader) # send the file output.seek(0) response.headers['Content-Type'] = 'text/html' output_name = os.path.splitext(input_data.original_name)[0] + '.html' return response.stream(output, 1048576, attachment=True, filename=output_name) return dict(form=form)
from cobra.io.sbml import create_cobra_model_from_sbml_file from html_writer import HtmlWriter import analysis_toolbox main_html = HtmlWriter('res/fba.html') main_html.write('<title>FBA</title>') main_html.write('<h1>FBA</h1>\n') model = create_cobra_model_from_sbml_file('data/iJO1366.xml') main_html.write('</ul>\n') print("Running standard FBA...") solution = model.optimize() if solution.status is not None: # write the flux summary for the knockout model as HTML analysis_toolbox.model_summary(model, solution, main_html) main_html.close()
def make_welcome_page(self, mailaddr, filename): db = Database() try: prob = db.get_properties('maildata') user_name = prob[mailaddr] writer = HtmlWriter(open(filename, mode='w')) writer.title('Welcome to ' + user_name + 'is page') writer.paragraph(user_name + 'のページへようこそ。') writer.paragraph('メール持っていますね。') writer.mailto(mailaddr, user_name) writer.close() print(filename + ' is created for' + mailaddr + ' (' + user_name + ')') except IOError as e: logging.exception(e)
def main(): main_html = HtmlWriter('res/fba.html') main_html.write('<h1>Flux Balance Analysis</h1>\n') carbon_sources = {} BM_lower_bound = 0.01 ko_reactions = '' ki_reactions = '' PPP_reaction = '' # full model carbon sources: glc, fru, xyl__D, succ, ac, rib__D, pyr ######################################### # Core model for testing glycolysis KOs # ######################################### #model = init_wt_model('core', {'ac' : -10}); ko_reactions = 'PGM'; ki_reactions = 'RED'; #model = init_wt_model('core', {'glc' : -10}); ko_reactions = 'PFK'; ki_reactions = 'RED'; ####################################### # Full model Rubisco optimization KOs # ####################################### #model = init_wt_model('full', {'ac' : -10}); ko_reactions = 'PGM,TRSARr,HPYRRx,HPYRRy'; ki_reactions = 'RED'; #model = init_wt_model('full', {'rib_D' : -10}); ko_reactions = 'TKT1'; ki_reactions = 'RBC,PRK'; PPP_reaction = 'RBC'; model = init_wt_model('full', {'xyl_D' : -10}); ko_reactions = 'RPI'; ki_reactions = 'RBC,PRK'; PPP_reaction = 'RBC'; #model = init_wt_model('full', {'xyl_D' : -10}); ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA'; ki_reactions = 'RBC,PRK'; #model = init_wt_model('full', {'fru' : -10, 'rib_D' : -10}); ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA,TKT1,TKT2'; ki_reactions = 'PKT'; ############################### # Shikimate generating strain # ############################### #model = init_wt_model('full', {'fru' : -10}); #ko_reactions = 'G6PDH2r,TALA'; ki_reactions = 'EX_3dhsk_c'; PPP_reaction = 'EX_3dhsk_c'; #ko_reactions = 'G6PDH2r,PFK,F6PA,FRUK,PFK_3,DRPA'; ki_reactions = 'PKT'; PPP_reaction = 'PKT'; ########################################################## # Testing no growth when electrons are provided directly # ########################################################## #model = init_wt_model('full', {}); ki_reactions = 'RED'; #ko_reactions = "POR5,MCITL2"; #ko_reactions = "POR5,FTHFLi,GART,RPI"; models = {'WT' : model} if ko_reactions: for k in models.keys(): m = deepcopy(models[k]) knockout_reactions(m, ko_reactions) models[k + ' -%s' % ko_reactions] = m if ki_reactions: for k in models.keys(): m = deepcopy(models[k]) knockin_reactions(m, ki_reactions) models[k + ' +%s' % ki_reactions] = m # Run the optimization for the objective reaction and medium composition # set in the file. main_html.write('<table border="1">\n') main_html.write('<tr><td><b>Model Name</b></td><td><b>Growth Yield</b></td></tr>\n') growths = {} for name, model in sorted(models.iteritems()): print "solving %50s model" % name, ok = OptKnock(model) ok.prepare_FBA_primal() ok.solve() growths[name] = ok.get_objective_value() if growths[name] is None: main_html.write('<tr><td>%s</td><td>infeasible</td></tr>\n' % name) else: print ': f = %.3g' % growths[name] main_html.write('<tr><td>') html = main_html.branch(name) main_html.write('</td><td>%.3g</td></tr>\n' % growths[name]) html.write('<h1>Model name: %s</h1>\n' % name) html.write('<h2>Growth Yield: %.3g</h2>\n' % growths[name]) ok.draw_svg(html) ok.model_summary(html) main_html.write('</table>\n') if PPP_reaction: print 'Calculating Phenotypic Phase Plane for phosphoketolase ...' fig, ax = plt.subplots(1, figsize=(6,6)) plot_multi_PPP(models, PPP_reaction, ax) ax.set_title('Phenotypic Phase Plane') main_html.embed_matplotlib_figure(fig, width=400, height=400)
def main(): Pentose_target_compounds = ['D-Xylulose-5P', 'D-Ribulose-5P', 'D-Ribose-5P'] PP_compounds = \ ['D-Xylulose-5P',\ 'D-Ribulose-5P',\ 'D-Ribose-5P',\ 'D-Erythrose-4P',\ 'D-Sedoheptulose-7P',\ 'D-Fructose-6P',\ 'D-Glyceraldehyde-3P'] Glycolysis_compounds = \ ['Dihydroxyacetone-3P',\ 'D-Glyceraldehyde-3P',\ 'Bisphosphoglycerate',\ '3-Phosphoglycerate',\ '2-Phosphoglycerate',\ 'Phosphoenolpyruvate',\ 'Pyruvate'] TCA_compounds = \ ['Oxaloacetate',\ 'Citrate',\ 'cis-Aconitate',\ 'D-Isocitrate',\ '2-Ketoglutarate',\ #succinyl-CoA\ 'Succinate',\ 'Fumarate',\ 'Malate',\ ] Biosynthese_compounds = PP_compounds + Glycolysis_compounds + TCA_compounds pathway_list = [] # fast test pathway_list.append(("TEST", ['2-Phosphoglycerate'], ['Bisphosphoglycerate'], None)) # Optimality Modules: pathway_list.append(("Glucose to Fructose", ['D-glucose-6P'], ['D-fructose-6P'], None)) pathway_list.append(("Fructose to Glucose", ['D-fructose-6P'], ['D-glucose-6P'], None)) pathway_list.append(("oxaloacetate+acetyl-CoA to citrate", ['oxaloacetate + acetyl-CoA'], ['citrate'], None)) pathway_list.append(("cis-aconitate to succinate", ['cis-aconitate'], ['succinate'], None)) pathway_list.append(("D-xylose to D-xylulose-5P", ['D-Xylose'], ['D-Xylulose-5P'], None)) pathway_list.append(("D-arabitol to D-xylulose-5P", ['D-Arabitol'], ['D-Xylulose-5P'], None)) pathway_list.append(("L-arabinose to D-xylulose-5P", ['L-Arabinose'], ['D-Xylulose-5P'], None)) pathway_list.append(("L-xylulose to D-xylulose-5P", ['L-Xylulose'], ['D-Xylulose-5P'], None)) pathway_list.append(("ribitol to D-xylulose-5P", ['Ribitol'], ['D-Xylulose-5P'], None)) pathway_list.append(("D-ribose to D-xylulose-5P", ['D-Ribose'], ['D-Xylulose-5P'], None)) pathway_list.append(("Oxaloacetate to 2-Ketoglutarate", ['Oxaloacetate'], ['2-Ketoglutarate'], None)) pathway_list.append(("Citrate to 2-Ketoglutarate", ['Citrate'], ['2-Ketoglutarate'], None)) pathway_list.append(("Pentose Phosphate", ['D-Xylulose-5P + D-Xylulose-5P + D-Ribose-5P'], ['D-Fructose-6P + D-Fructose-6P + D-Glyceraldehyde-3P'], None)) #pathway_list.append(("Pentose Phosphate", ['D-Xylulose-5P + D-Ribose-5P'], ['D-Glyceraldehyde-3P + D-Sedoheptulose-7P'], None)) pathway_list.append(("D-glucose to D-ribulose-5P", ['D-Glucose'], ['D-Ribulose-5P'], None)) pathway_list.append(("D-glucose to D-fructose-16P", ['D-Glucose'], ['D-Fructose-16P'], None)) pathway_list.append(("D-fructose-6P to GAP+DHAP", ['D-Fructose-6P'], ['D-Glyceraldehyde-3P + Dihydroxyacetone-3P'], None)) pathway_list.append(("GAP to 3-PG", ['D-Glyceraldehyde-3P'], ['3-Phosphoglycerate'], None)) pathway_list.append(("GAP to 2-PG", ['D-Glyceraldehyde-3P'], ['2-Phosphoglycerate'], None)) pathway_list.append(("BPG to 3-PG", ['Bisphosphoglycerate'], ['3-Phosphoglycerate'], None)) pathway_list.append(("BPG to 2-PG", ['Bisphosphoglycerate'], ['2-Phosphoglycerate'], None)) pathway_list.append(("BPG to PEP", ['Bisphosphoglycerate'], ['Phosphoenolpyruvate'], None)) pathway_list.append(("3-PG to PYR", ['3-Phosphoglycerate'], ['Pyruvate'], None)) # Biosynthesis pathway_list.append(("3-PG to L-Serine", ['3-Phosphoglycerate'], ['L-Serine'], None)) pathway_list.append(("L-Serine to Glycine", ['L-Serine'], ['Glycine'], None)) pathway_list.append(("Pyruvate to L-Alanine", ['Pyruvate'], ['L-Alanine'], None)) pathway_list.append(("Synthesis of L-Serine", Biosynthese_compounds, ['L-Serine'], None)) pathway_list.append(("Synthesis of L-Alanine", Biosynthese_compounds, ['L-Alanine'], None)) pathway_list.append(("Synthesis of Glycine", Biosynthese_compounds, ['Glycine'], None)) pathway_list.append(("Synthesis of L-Aspartate", Biosynthese_compounds, ['L-Aspartate'], None)) pathway_list.append(("Synthesis of L-Glutamate", Biosynthese_compounds, ['L-Glutamate'], None)) # Pentose utilization pathway_list.append(("L-Arabinose to Pentose Phosphate", ['L-Arabinose'], Pentose_target_compounds, None)) pathway_list.append(("D-Xylose to Pentose Phosphate", ['D-Xylose'], Pentose_target_compounds, None)) pathway_list.append(("D-Ribose to Pentose Phosphate", ['D-Ribose'], Pentose_target_compounds, None)) pathway_list.append(("Ribitol to Pentose Phosphate", ['Ribitol'], Pentose_target_compounds, None)) pathway_list.append(("D-Arabitol to Pentose Phosphate", ['D-Arabitol'], Pentose_target_compounds, None)) # Glycolysis pathway_list.append(("GAP to PYR", ['D-Glyceraldehyde-3P'], ['Pyruvate'], 'PP')) pathway_list.append(("GAP to DHAP", ['D-Glyceraldehyde-3P'], ['Dihydroxyacetone-3P'], 'PP')) pathway_list.append(("GAP to PEP", ['D-Glyceraldehyde-3P + H2O'], ['Phosphoenolpyruvate + H2O'], 'PP')) pathway_list.append(("GAP to 2-PG", ['D-Glyceraldehyde-3P'], ['2-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC to GAP", ['D-Glucose'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append(("GLC to PYR", ['Glucose'], ['Pyruvate + Pyruvate'], 'PP')) pathway_list.append(("GLC-36P to GAP", ['D-Glucose-36P'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append(("GLC-6P to GAP", ['D-Glucose-6P'], ['D-Glyceraldehyde-3P + D-Glyceraldehyde-3P'], 'PP')) pathway_list.append(("GLC-6P to BPG", ['D-Glucose-6P'], ['Bisphosphoglycerate + Bisphosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to 3-PG", ['D-Glucose-6P'], ['3-Phosphoglycerate + 3-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to 2-PG", ['D-Glucose-6P'], ['2-Phosphoglycerate + 2-Phosphoglycerate'], 'PP')) pathway_list.append(("GLC-6P to PEP", ['D-Glucose-6P'], ['Phosphoenolpyruvate + Phosphoenolpyruvate'], 'PP')) pathway_list.append(("2-PG to PYR", ['2-Phosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append(("3-PG to PYR", ['3-Phosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append(("BPG to PYR", ['Bisphosphoglycerate'], ['Pyruvate'], 'PP')) pathway_list.append(("BPG to PEP", ['Bisphosphoglycerate'], ['Phosphoenolpyruvate'], 'PP')) # Arren's project pathway_list.append(("Glyoxylate + GAP to Pentose", ['Glyoxylate + D-Glyceraldehyde-3P'], Pentose_target_compounds, None)) pathway_list.append(("Glyoxylate + PYR to Pentose", ['Glyoxylate + Pyruvate'], Pentose_target_compounds, None)) pathway_list.append(("Glycolate + GAP to Pentose", ['Glycolate + D-Glyceraldehyde-3P'], Pentose_target_compounds, None)) pathway_list.append(("Glycolate + PYR to Pentose", ['Glycolate + Pyruvate'], Pentose_target_compounds, None)) pathway_names = [pathway[0] for pathway in pathway_list] pathway_map = {} for pathway in pathway_list: pathway_map[pathway[0]] = pathway[1:] if (len(sys.argv) > 1): pathway_name = pathway_names[int(sys.argv[1]) - 1] else: pathway_name = TkListSelection(pathway_names, "Choose a pathway:") if (pathway_name == None): sys.exit(0) (substrates, products, pruning_method) = pathway_map[pathway_name] pathfinder = PathFinder(carbon_only=False, pruning_method=pruning_method, ignore_chirality=True) print "-"*80 + "\nChosen pathway name is %s\n" % pathway_name + "-"*80 util._mkdir("../results") util._mkdir("../results/" + pathway_name) html_writer = HtmlWriter("../results/" + pathway_name + ".html") html_writer.write("<h1><center>%s</center></h1>\n" % pathway_name) html_writer.write("<ul>\n") for i in range(len(substrates)): for j in range(len(products)): ##(subs, prod) = pathfinder.balance_reaction(substrates[i], products[j]) (subs, prod) = (substrates[i], products[j]) pathway_prefix = "pathway_%d_%d" % (i, j) util._mkdir("../results/" + pathway_name + "/" + pathway_prefix) pathfinder.solve_pathway(subs, prod, html_writer, pathway_name, pathway_prefix, max_levels=6, stop_after_first_solution=True) html_writer.flush() html_writer.write("</ul>\n") html_writer.display() return
max_recipients = 1560 max_heatmap_index = 8.0 html_file = os.path.join(output_dir, 'overlap.html') html_fp = open(html_file, 'w') json_fp = open(json_file, 'rb') results = json.load(json_fp) all_results = {} funders = results.keys() funders.sort() html_writer = HtmlWriter(html_fp) html_writer.open_tag('html') html_writer.open_tag('head') html_writer.empty_tag('link', {'href': 'style.css', 'rel':'stylesheet'}) html_writer.empty_tag('link', {'href': 'overlap.css', 'rel':'stylesheet'}) html_writer.close_tag('head') html_writer.open_tag('body') html_writer.open_tag('div', {'class': 'container'}) html_writer.write_html('h1', 'Overlap between funders') html_writer.open_tag('table') html_writer.open_tag('tr')
sns.set() sns.axes_style("darkgrid") l = logging.getLogger() l.setLevel(logging.INFO) exp_name = "ecoli_ccm_aerobic_channeling" DATA_DIR = os.path.expanduser("~/git/enzyme-cost/data") RES_DIR = os.path.expanduser("~/git/enzyme-cost/res") model_sbtab_fpath = os.path.join(DATA_DIR, "%s_ModelData.csv" % exp_name) verify_sbtab_fpath = os.path.join(DATA_DIR, "%s_ValidationData.csv" % exp_name) sqlite_fpath = os.path.join(RES_DIR, "%s.sqlite" % exp_name) mat_fpath = os.path.join(RES_DIR, "%s.mat" % exp_name) html_fpath = os.path.join(RES_DIR, "%s.html" % exp_name) html = HtmlWriter(html_fpath) logging.info("Converting input data from SBtab to SQLite") _model_sbtab_dict = SBtabDict.FromSBtab(model_sbtab_fpath) _verify_sbtab_dict = SBtabDict.FromSBtab(verify_sbtab_fpath) comm = sqlite3.connect(sqlite_fpath) _model_sbtab_dict.SBtab2SQL(comm, append=False) _verify_sbtab_dict.SBtab2SQL(comm, append=False) comm.commit() comm.close() logging.info("Reading data from SQLite database: " + sqlite_fpath) sbtab_dict = SBtabDict.FromSQLite(sqlite_fpath) logging.info("Creating an ECM model using the data") model = ECMmodel(sbtab_dict, dG0_source="keq_table") logging.info("Exporting data to .mat file: " + mat_fpath)
class Pathologic: def __init__(self, modules_file, experiment_name, max_module_size=6): self.modules_file = modules_file self.experiment_name = experiment_name self.max_module_size = max_module_size util._mkdir("../log") self.logfile = open( "../log/pathologic_" + self.experiment_name + ".log", "w") util._mkdir("../results") util._mkdir("../results/pathologic_" + self.experiment_name) self.html_writer = HtmlWriter("../results/pathologic_" + self.experiment_name + ".html") self.html_writer.write( "<h1>List of optimal and non-optimal pathways</h1>\n") self.html_writer.write("<ul>\n") self.line_counter = 0 self.pathfinder = None def find_shortest_pathways(self, substrate, product, max_levels, stop_after_first_solution=True): G_subs = compound2graph(substrate) G_prod = compound2graph(product) return self.pathfinder.find_shortest_pathway( [G_subs], [G_prod], max_levels=max_levels, stop_after_first_solution=stop_after_first_solution) def get_distance(self, substrate, product, max_levels): G_subs = compound2graph(substrate) G_prod = compound2graph(product) return self.pathfinder.find_distance([G_subs], [G_prod], max_levels=max_levels) def get_all_pathways(self, substrate, product, max_levels): """return all existing pathways with a length <= max_distance. """ (original_compound_map, possible_pathways, min_length) = self.find_shortest_pathways( substrate, product, max_levels=max_levels, stop_after_first_solution=False) if (possible_pathways == []): return [] else: scene_list = self.pathfinder.get_all_possible_scenes( original_compound_map, possible_pathways) return [scene for (cost, scene) in scene_list ] # strip off the cost of each pathway def get_shortest_pathways(self, substrate, product, max_levels): """return -1 if the is no path with length <= max_levels. otherwise a pair containing a list of all pathways with the minimal length and the minimal length itself """ (original_compound_map, possible_pathways, min_length) = self.find_shortest_pathways( substrate, product, max_levels=max_levels, stop_after_first_solution=True) if (possible_pathways == []): return ([], -1) else: scene_list = self.pathfinder.get_all_possible_scenes( original_compound_map, possible_pathways) return ([scene for (cost, scene) in scene_list], min_length ) # strip off the cost of each pathway def verify_pathway(self, pathway): sys.stdout.write("Verifying pathway: %s\n" % str(pathway)) for i in range(len(pathway) - 1): sys.stdout.write(" - checking '%s' -> '%s' ... " % tuple(pathway[i:i + 2])) sys.stdout.flush() distance = self.get_distance(pathway[i], pathway[i + 1], 1) if (distance == -1): sys.stdout.write("FAILED (not neighbors)\n") else: sys.stdout.write("OK\n") sys.stdout.flush() def is_optimal(self, pathway, i, j, draw_scenes=False): sys.stdout.write(str(pathway[i:j + 1]) + " ... ") wt_distance = j - i if (wt_distance <= 1): # we have verified that this is optimal already return True if (draw_scenes): # try to find at least one path which is shorter than the wild-type path: (scenes, dist) = self.get_shortest_pathways(pathway[i], pathway[j], wt_distance - 1) else: dist = self.get_distance(pathway[i], pathway[j], wt_distance - 1) if ( dist == -1 ): # which means no shorter path has been found, hence the WT pathway is one of the shortest sys.stdout.write(" is optimal!\n") self.html_writer.write( "<li><span style=color:green>%s - OPTIMAL</span></li>\n" % str(pathway[i:j + 1])) self.html_writer.flush() return True else: # there is a shorter path than the WT one sys.stdout.write(" is not optimal!\n") self.html_writer.write( "<li>\n <span style=color:red>%s - NOT OPTIMAL</span><br>\n " % str(pathway[i:j + 1])) if (draw_scenes): #for s in scenes: s = scenes[ 0] # draws only the first scene (otherwise it could be too long) self.html_writer.write_svg( s, "pathologic_" + self.experiment_name + "/pathway_%d_%d_%d" % (self.line_counter, i, j)) self.html_writer.write("\n</li>\n") self.html_writer.flush() return False def find_modules(self, pathway, draw_scenes=False): self.verify_pathway(pathway) i = 0 for j in range(2, len(pathway)): if (j - i >= self.max_module_size): sys.stdout.write( str(pathway[i:(j + 1)]) + " is too long for me, chopping off the head...\n") i += 1 # shorten the path from it's head until it is optimal (or too short, i.e. length=1) while ( (j - i) > 1 and (not self.is_optimal(pathway, i, j, draw_scenes=draw_scenes))): i += 1 def analyze(self, carbon_only=True, use_antimotifs=True, draw_scenes=False): for line in util.parse_text_file("../rec/" + self.modules_file + ".txt"): if (line[0] == '@'): line = line[1:] self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=False, use_antimotifs=use_antimotifs, outstream=self.logfile) else: self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=True, use_antimotifs=use_antimotifs, outstream=self.logfile) pathway = line.split(';') self.find_modules(pathway, draw_scenes=draw_scenes) self.line_counter += 1 def analyze_pairs(self, carbon_only=True, use_antimotifs=True, max_distance=4): distances = [ ] # the minimal pathway length between the substrate and the product alternatives = [ ] # each value is the number of alternative pathways with the minimal distance line_counter = 0 for line in util.parse_text_file("../rec/" + self.modules_file + ".txt"): if (line[0] == '@'): line = line[1:] self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=False, use_antimotifs=use_antimotifs, outstream=self.logfile) else: self.pathfinder = PathFinder(carbon_only=carbon_only, pruning_method=None, ignore_chirality=True, use_antimotifs=use_antimotifs, outstream=self.logfile) (subs, prod, max_steps) = line.split(";", 2) if (max_steps in ['-1', 'inf', '']): sys.stdout.write(subs + " -(?)-> " + prod) sys.stdout.flush() (scenes, dist) = self.get_shortest_pathways(subs, prod, max_distance) else: dist = int(max_steps) sys.stdout.write(subs + " -(%d)-> " % dist + prod) sys.stdout.flush() scenes = self.get_all_pathways(subs, prod, dist) if (dist == -1): sys.stdout.write(", Distance(L) = inf, N = 0\n") sys.stdout.flush() distances.append("inf") alternatives.append(0) self.html_writer.write( "<li><span style=color:red>%s <-> %s (distance > %d)</span></li>\n" % (subs, prod, self.max_module_size)) self.html_writer.flush() else: sys.stdout.write(", Distance(L) = %d, N = %d\n" % (dist, len(scenes))) sys.stdout.flush() distances.append(dist) alternatives.append(len(scenes)) self.html_writer.write( "<li><span style=color:green>%s <-> %s (distance = %d)</span></li>\n" % (subs, prod, dist)) for i in range(len(scenes)): self.html_writer.write("<li>") self.html_writer.write_svg( scenes[i], "pathologic_" + self.experiment_name + "/pair%d_path%d" % (line_counter, i)) self.html_writer.write("</li>\n") self.html_writer.flush() line_counter += 1 result_file = open("../results/" + self.experiment_name + ".txt", "w") result_file.write(str(distances) + "\n" + str(alternatives) + "\n") result_file.close() def display(self): self.html_writer.write("</ul>\n") self.html_writer.write(self.pathfinder.reactor.antimotif_summary()) self.html_writer.display() def __del__(self): del self.pathfinder self.logfile.close()