def test_Builder(tmpdir): b = Builder(map_json='{"r": "val"}', model_json='{"r": "val"}') # Cannot load dev/local version without an explicit css string property. # TODO include a test where these do not raise. with raises(Exception): b.display_in_notebook(js_source='dev') with raises(Exception): b.display_in_notebook(js_source='local') # ok with embedded_css arg b = Builder(map_json='{"r": "val"}', model_json='{"r": "val"}', embedded_css='') b.display_in_notebook(js_source='dev') b.save_html(join(str(tmpdir), 'Builder.html'), js_source='dev') # test options with raises(Exception): b._get_html(js_source='devv') with raises(Exception): b._get_html(menu='') with raises(Exception): b._get_html(scroll_behavior='asdf') b._get_html(js_source='local') b._get_html(menu='all') b._get_html(scroll_behavior='zoom')
def test_Builder_download(): # download b = Builder(map_name='iJO1366.Central metabolism', model_name='iJO1366') assert b.loaded_map_json is not None assert b.loaded_model_json is not None b._get_html(js_source='web') # b.display_in_notebook(height=200) # data b = Builder(map_name='iJO1366.Central metabolism', model_name='iJO1366', reaction_data=[{ 'GAPD': 123 }, { 'GAPD': 123 }]) b = Builder(map_name='iJO1366.Central metabolism', model_name='iJO1366', metabolite_data=[{ 'nadh_c': 123 }, { 'nadh_c': 123 }]) b = Builder(map_name='iJO1366.Central metabolism', model_name='iJO1366', gene_data=[{ 'gapA': 123 }, { 'adhE': 123 }]) assert type(b.the_id) is unicode_type assert len(b.the_id) == 10
def test__draw_js(): b = Builder(map_json='"useless_map"', model_json='"useless_model"', embedded_css='') def look_for_string(st, substring): """Look for the string in the substring. This solves a bug in py.test for these cases""" try: found = st.find(substring) assert found > -1 except AssertionError: raise AssertionError('Could not find\n\n%s\n\nin\n\n%s' % (substring, st)) # no static parse, dev ijs = b._initialize_javascript('id', 'local') js = b._draw_js('id', True, 'all', True, True, True, 'pan', True, None) look_for_string(ijs, 'var map_data_id = "useless_map";') look_for_string(ijs, 'var model_data_id = "useless_model";') look_for_string(js, 'Builder(map_data_id, model_data_id, embedded_css_id, d3.select("#id"), options);') # static parse, not dev ijs = b._initialize_javascript('id', 'local') static_index = '{"my": ["useless", "index"]}' js = b._draw_js('id', True, 'all', True, False, True, 'pan', True, static_index) look_for_string(ijs, 'var map_data_id = "useless_map";') look_for_string(ijs, 'var model_data_id = "useless_model";') look_for_string(js, 'escher.static.load_map_model_from_url("%s/maps/", "%s/models/",' % (__schema_version__, __schema_version__)) look_for_string(js, static_index) look_for_string(js, 'options, function(map_data_id, model_data_id, options) {') look_for_string(js, 'escher.Builder(map_data_id, model_data_id, embedded_css_id, d3.select("#id"), options);')
def test_save_html(tmpdir): # ok with embedded_css arg b = Builder(map_json='"useless_map"', model_json='"useless_model"', embedded_css='') filepath = join(str(tmpdir), 'builder.html') b.save_html(filepath) def look_for_string(st, substring): """Look for the string in the substring. This solves a bug in py.test for these cases""" try: found = st.find(substring) assert found > -1 except AssertionError: raise AssertionError('Could not find\n\n%s\n\nin\n\n%s' % (substring, st)) # no static parse, local with open(filepath, 'r') as f: html = f.read() look_for_string( html, 'map_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbWFwIg==\')),', ) look_for_string( html, 'model_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbW9kZWwi\')),', ) look_for_string( html, 'escher.Builder(data.map_data, data.model_data, ', )
def draw_knockout_result(model, map_name, simulation_method, knockouts, *args, **kwargs): with model: for reaction in model.reactions.get_by_any(knockouts): reaction.knock_out() solution = simulation_method(model, *args, **kwargs).fluxes return Builder(map_name, reaction_data=solution)
def test__get_html(): b = Builder(map_json='"useless_map"', model_json='"useless_model"', embedded_css='') def look_for_string(st, substring): """Look for the string in the substring. This solves a bug in py.test for these cases""" try: found = st.find(substring) assert found > -1 except AssertionError: raise AssertionError('Could not find\n\n%s\n\nin\n\n%s' % (substring, st)) # no static parse, local html = b._get_html(js_source='local') look_for_string(html, 'map_data: JSON.parse(\'"useless_map"\'),') look_for_string(html, 'model_data: JSON.parse(\'"useless_model"\'),') look_for_string(html, 'escher.Builder(t_map_data, t_model_data, data.builder_embed_css,') # static parse, not dev static_index = '{"my": ["useless", "index"]}' html = b._get_html(static_site_index_json=static_index, protocol='https') look_for_string(html, 'map_data: JSON.parse(\'"useless_map"\'),') look_for_string(html, 'model_data: JSON.parse(\'"useless_model"\'),') look_for_string(html, 'map_download_url: JSON.parse(\'"https://escher.github.io/%s/%s/maps/"\'),' % (__schema_version__, __map_model_version__)) look_for_string(html, 'model_download_url: JSON.parse(\'"https://escher.github.io/%s/%s/models/"\'),' % (__schema_version__, __map_model_version__)) look_for_string(html, static_index) look_for_string(html, 'escher.Builder(t_map_data, t_model_data, data.builder_embed_css,')
def test__get_html(): b = Builder(map_json='"useless_map"', model_json='"useless_model"', embedded_css='') def look_for_string(st, substring): """Look for the string in the substring. This solves a bug in py.test for these cases""" try: found = st.find(substring) assert found > -1 except AssertionError: raise AssertionError('Could not find\n\n%s\n\nin\n\n%s' % (substring, st)) # no static parse, local html = b._get_html(js_source='local') look_for_string( html, 'map_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbWFwIg==\')),') look_for_string( html, 'model_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbW9kZWwi\')),') look_for_string( html, 'escher.Builder(t_map_data, t_model_data, data.builder_embed_css,') # static parse, not dev static_index = '{"my": ["useless", "index"]}' html = b._get_html(static_site_index_json=static_index, protocol='https') look_for_string( html, 'map_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbWFwIg==\')),') look_for_string( html, 'model_data: JSON.parse(b64DecodeUnicode(\'InVzZWxlc3NfbW9kZWwi\')),') map_download_url = base64.b64encode( ("https://escher.github.io/%s/%s/maps/" % (__schema_version__, __map_model_version__)).encode('utf-8')).decode('utf-8') look_for_string( html, 'map_download_url: b64DecodeUnicode(\'%s\'),' % map_download_url) model_download_url = base64.b64encode( ("https://escher.github.io/%s/%s/models/" % (__schema_version__, __map_model_version__)).encode('utf-8')).decode('utf-8') look_for_string( html, 'model_download_url: b64DecodeUnicode(\'%s\'),' % model_download_url) look_for_string(html, 'eyJteSI6IFsidXNlbGVzcyIsICJpbmRleCJdfQ==') # static_index look_for_string( html, 'escher.Builder(t_map_data, t_model_data, data.builder_embed_css,')
def test_save_html_embedded_css(tmpdir): # ok with embedded_css arg b = Builder(embedded_css='useless_css') filepath = join(str(tmpdir), 'builder.html') b.save_html(filepath) with open(filepath, 'r') as f: html = f.read() look_for_string( html, "embedded_css = b64DecodeUnicode('dXNlbGVzc19jc3M=')", )
def test_Builder(tmpdir): # ok with embedded_css arg b = Builder(map_json='{"r": "val"}', model_json='{"r": "val"}', embedded_css='') b.display_in_notebook(js_source='local') b.save_html(join(str(tmpdir), 'Builder.html'), js_source='local') # test options with raises(Exception): b._get_html(js_source='devv') with raises(Exception): b._get_html(menu='') with raises(Exception): b._get_html(scroll_behavior='asdf') b._get_html(js_source='local') b._get_html(menu='all') b._get_html(scroll_behavior='zoom')
def plot_fluxes( flux_dict, escher_map, output_file='map.html', height=600, width=800, reaction_scale=None, min_flux=-10, max_flux=10, ): if min_flux is None: min_flux = min(flux_dict) if max_flux is None: max_flux = max(flux_dict) if reaction_scale is None: reaction_scale = [{ 'type': 'value', 'value': min_flux, 'color': 'red', 'size': 32 }, { 'type': 'value', 'value': 0, 'color': '#c8c8c8', 'size': 12 }, { 'type': 'value', 'value': max_flux, 'color': 'green', 'size': 32 }] builder = Builder(height=height, width=width, map_json=escher_map, reaction_scale=reaction_scale) builder.reaction_data = flux_dict builder.save_html(output_file) builder.close()
def test_save_html(tmpdir): b = Builder(map_json='"useless_map"', model_json='"useless_model"') filepath = join(str(tmpdir), 'builder.html') b.save_html(filepath) with open(filepath, 'r') as f: html = f.read() look_for_string( html, 'escher.Builder(data.map_data, data.model_data, ', ) look_for_string( html, "map_data = JSON.parse(b64DecodeUnicode('InVzZWxlc3NfbWFwIg=='))", ) look_for_string( html, "model_data = JSON.parse(b64DecodeUnicode('InVzZWxlc3NfbW9kZWwi'))", ) assert 'embedded_css =' not in html
def draw_knockout_result(model, map_name, simulation_method, knockouts, *args, **kwargs): tm = TimeMachine() try: for reaction in model._ids_to_reactions(knockouts): tm(do=partial(setattr, reaction, 'lower_bound', 0), undo=partial(setattr, reaction, 'lower_bound', reaction.lower_bound)) tm(do=partial(setattr, reaction, 'upper_bound', 0), undo=partial(setattr, reaction, 'upper_bound', reaction.upper_bound)) solution = simulation_method(model, *args, **kwargs).x_dict tm.reset() return Builder(map_name, reaction_data=solution) except Exception as e: tm.reset() raise e
def animate_fluxes( flux_time_data, escher_map, outputfile='animation.mp4', height=600, width=800, time_interval_ms=100, chrome=DEFAULT_CHROME, reaction_scale=None, min_flux=None, max_flux=None, time_size=12, time_unit='h', x_time=0.95, y_time=0.9, ): if min_flux is None: min_flux = flux_time_data.min().min() if max_flux is None: max_flux = flux_time_data.max().max() if reaction_scale is None: reaction_scale = [{ 'type': 'value', 'value': min_flux, 'color': 'red', 'size': 32 }, { 'type': 'value', 'value': 0, 'color': '#c8c8c8', 'size': 12 }, { 'type': 'value', 'value': max_flux, 'color': 'green', 'size': 32 }] builder = Builder(height=height, width=width, map_json=escher_map, embedd_css=EMBEDD_CSS, menu='none', reaction_scale=reaction_scale) myimages = [] fig = plt.figure() XVFB_DOCKER = '/usr/bin/xvfb-run -a -s \"-screen 0 {}x{}x24\"'.format( width, height) SCREENSHOT = "--headless --disable-gpu --no-sandbox --virtual-time-budget=10000 --screenshot=\'{}\' {}" for t, fluxes in flux_time_data.iterrows(): builder.reaction_data = fluxes builder.save_html('tmp.html', ) # Hacky hack hack ... # Use chrome to make a screenshot cmd = "{} {} {}".format(XVFB_DOCKER, chrome, SCREENSHOT.format('tmp.png', 'tmp.html')) os.system(cmd) # Add time text ylim = plt.gca().get_ylim() xlim = plt.gca().get_xlim() y = (ylim[1] - ylim[0]) * y_time + ylim[0] x = (xlim[1] - xlim[0]) * x_time + xlim[0] text = plt.text(x, y, '{:.1f} {}'.format(t, time_unit), horizontalalignment='right', fontsize=time_size) img = mgimg.imread('tmp.png') imgplot = plt.imshow(img) # append AxesImage object to the list myimages.append([imgplot, text]) plt.axis('off') fig.tight_layout() anim = animation.ArtistAnimation(fig, myimages, interval=time_interval_ms) anim.save(outputfile, dpi=300) builder.close()
def test_Builder_options(): b = Builder(embedded_css='') b.set_metabolite_no_data_color('white') assert b.metabolite_no_data_color == 'white'
import escher from escher import Builder import cobra from time import sleep escher.rc['never_ask_before_quit'] = True builder = Builder( map_name='e_coli_core.Core metabolism', model_name='e_coli_core', ) builder builder = Builder( map_name='iMM904.Central carbon metabolism', model_name='iMM904', ) builder builder = Builder(map_name= 'iJO1366.Fatty acid beta-oxidation') builder builder = Builder(model_json="Recon3D.json", map_name= 'RECON1.Carbohydrate metabolism') builder.save
import escher from escher import Builder import cobra from time import sleep escher.rc['never_ask_before_quit'] = True Core = Builder( map_name='e_coli_core.Core metabolism', model_name='e_coli_core', ) Core.save_html("Core.html") CarbonMeta = Builder(model_json="Recon3D.json", map_name='RECON1.Carbohydrate metabolism') CarbonMeta.save_html("CarbonMeta.html") FattyAcid = Builder( model_name='iMM904', map_name='iJO1366.Fatty acid beta-oxidation', ) FattyAcid.save_html("FattyAcid.html") EMP_TCA_PPP = Builder(map_name='RECON1.Glycolysis TCA PPP') EMP_TCA_PPP.save_html
def test_handling_cobra_fluxes(data, expected): b = Builder(reaction_data=data, gene_data=data, metabolite_data=data) assert b.reaction_data == expected assert b.gene_data == expected assert b.metabolite_data == expected
def test_Builder_options(): b = Builder(metabolite_no_data_color='blue') assert b.metabolite_no_data_color == 'blue' b.metabolite_no_data_color = 'white' assert b.metabolite_no_data_color == 'white'
def test_Builder_options(): b = Builder(embedded_css='') b.set_metabolite_no_data_color('white') assert b.metabolite_no_data_color=='white' html = b._get_html(js_source='local') assert 'metabolite_no_data_color: "white"' in html
import escher from escher import Builder import cobra from time import sleep escher.rc['never_ask_before_quit'] = True builder = Builder() builder get_ipython().getoutput("wget -nc http://bigg.ucsd.edu/static/models/iAB_RBC_283.json") builder = Builder( model_json='iAB_RBC_283.json' ) builder escher.list_available_maps() escher.list_available_models()
import escher from escher import Builder import cobra from time import sleep escher.rc['never_ask_before_quit'] = True Core = Builder( map_name='e_coli_core.Core metabolism', model_name='e_coli_core', ) Core model = cobra.io.load_json_model('e_coli_core.json') reverse = True step = 0.1 timestep = 0.1 duration = 1500 # seconds lim = [0, 0.5] val = lim[-1] for _ in range(int(duration / timestep)): model.reactions.EX_o2_e.lower_bound = -val solution = model.optimize() Core.reaction_data = solution.fluxes if val <= lim[0]: reverse = True if val >= lim[1]: reverse = False if reverse: val += step else: val -= step
# installed, escher makes downloading and viewing metabolic maps from a # [repository](https://github.com/zakandrewking/escher/tree/gh-pages/maps) # extremely simple. For more information, view the escher documentation. # # This example is also available as an IPython [notebook](http://nbviewer.ipyth # on.org/github/opencobra/cobrapy/blob/master/documentation_builder/escher.ipyn # b) from escher import Builder import cobra.test model = cobra.test.create_test_model(cobra.test.ecoli_pickle) cobra.flux_analysis.parsimonious.optimize_minimal_flux(model) wt_solution = model.solution.x_dict # mutant flux has PGI knocked out model.reactions.PGI.lower_bound = 0 model.reactions.PGI.upper_bound = 0 cobra.flux_analysis.parsimonious.optimize_minimal_flux(model) mutant_solution = model.solution.x_dict wt_map = Builder("iJO1366_central_metabolism", reaction_data=wt_solution) wt_map.display_in_notebook() wt_map = Builder("iJO1366_central_metabolism", reaction_data=mutant_solution) wt_map.display_in_notebook() # In a non-notebook environment, metabolic maps can still be viewed by running mutant_map.display_in_browser()