Example #1
0
def test_paths():
    net_flux = np.array([[0.0, 0.5, 0.5, 0.0, 0.0, 0.0],
                         [0.0, 0.0, 0.0, 0.3, 0.0, 0.2],
                         [0.0, 0.0, 0.0, 0.0, 0.5, 0.0],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.3],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])

    sources = np.array([0])
    sinks = np.array([4, 5])

    ref_paths = [[0, 2, 4],
                 [0, 1, 3, 5],
                 [0, 1, 5]]

    ref_fluxes = np.array([0.5, 0.3, 0.2])

    res_bottle = tpt.paths(sources, sinks, net_flux, remove_path='bottleneck')
    res_subtract = tpt.paths(sources, sinks, net_flux, remove_path='subtract')

    for paths, fluxes in [res_bottle, res_subtract]:
        npt.assert_array_almost_equal(fluxes, ref_fluxes)
        assert len(paths) == len(ref_paths)

        for i in range(len(paths)):
            npt.assert_array_equal(paths[i], ref_paths[i])
Example #2
0
def test_paths():

    net_flux = np.array([[0.0, 0.5, 0.5, 0.0, 0.0, 0.0],
                         [0.0, 0.0, 0.0, 0.3, 0.0, 0.2],
                         [0.0, 0.0, 0.0, 0.0, 0.5, 0.0],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.3],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                         [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])

    sources = np.array([0])
    sinks = np.array([4, 5])

    ref_paths = [[0, 2, 4], [0, 1, 3, 5], [0, 1, 5]]

    ref_fluxes = np.array([0.5, 0.3, 0.2])

    res_bottle = tpt.paths(sources, sinks, net_flux, remove_path='bottleneck')
    res_subtract = tpt.paths(sources, sinks, net_flux, remove_path='subtract')

    for paths, fluxes in [res_bottle, res_subtract]:
        npt.assert_array_almost_equal(fluxes, ref_fluxes)
        assert len(paths) == len(ref_paths)

        for i in xrange(len(paths)):
            npt.assert_array_equal(paths[i], ref_paths[i])
Example #3
0
def generate_tpt_traj_index_series(msm_object, sources, sinks, clusters_map,
                                   num_paths, remove_path, save_file):
    net_flux = tpt.net_fluxes(sources, sinks, msm_object)
    tpt_paths = tpt.paths(sources,
                          sinks,
                          net_flux,
                          remove_path=remove_path,
                          num_paths=num_paths,
                          flux_cutoff=0.5)

    inv_map = {v: k for k, v in msm_object.mapping_.items()}

    print(tpt_paths)
    traj_index_pairs_list = []
    for path in tpt_paths[0]:
        print("path = %s" % (str(path)))
        traj_index_pairs = []
        for state in path:
            cluster = inv_map[state]
            traj_index_pair = random.choice(list(clusters_map[cluster]))
            traj_index_pairs.append(traj_index_pair)
        traj_index_pairs_list.append(traj_index_pairs)

    verbosedump(traj_index_pairs_list, save_file)

    inv_tpt_paths = []
    for tpt_path in tpt_paths[0]:
        inv_tpt_paths.append([inv_map[i] for i in tpt_path])
    return tpt_paths[0], inv_tpt_paths, traj_index_pairs_list
Example #4
0
def make_json_paths(msm, request):
    sources = map(int,
                  request.get_argument('sources').replace(" ", "").split(","))
    sinks = map(int, request.get_argument('sinks').replace(" ", "").split(","))
    n = int(request.get_argument('num_paths'))
    net_flux = tpt.net_fluxes(sources, sinks, msm)
    paths = tpt.paths(sources, sinks, net_flux, num_paths=n)
    G = nx.DiGraph()
    for j, i in enumerate(paths[0][::-1]):
        G.add_node(i[0], type="source")
        for k in range(1, len(i)):
            G.add_node(i[k], type="none")
            G.add_edge(i[k-1], i[k], weight=paths[1][::-1][j])
        G.add_node(i[-1], type="sink")
    return json_graph.node_link_data(G)
Example #5
0
def plot_tpaths(
    msm, sources, sinks, for_committors=None, num_paths=1, pos=None, node_color="c", edge_color="k", ax=None, **kwargs
):

    net_flux = tpt.net_fluxes(sources, sinks, msm, for_committors=for_committors)
    paths, _ = tpt.paths(sources, sinks, net_flux, num_paths=num_paths)

    graph = nx.DiGraph()
    for path in paths:
        for u, v in zip(path[:-1], path[1:]):
            graph.add_edge(u, v, weight=net_flux[u, v])

    if not ax:
        ax = pp.gca()

    nx.draw_networkx(graph, pos=pos, node_color=node_color, edge_color=edge_color, ax=ax, **kwargs)

    return ax
Example #6
0
def do_tpt(ev_id):
    plt.figure(figsize=(15, 10))
    # TPT "FROM":
    sources = [7]
    # TPT "To":
    sinks = [10]
    net_flux = tpt.net_fluxes(sources, sinks, msm, for_committors=None)
    np.savetxt('net_flux.txt', net_flux)
    pfold = tpt.committors(sources, sinks, msm)
    np.savetxt('pfold.txt', pfold)
    paths = tpt.paths(sources,
                      sinks,
                      net_flux,
                      remove_path='subtract',
                      flux_cutoff=0.9999999999)
    mfpts = tpt.mfpts(
        msm, sinks=None, lag_time=1.0
    )  #     Default is (1) which is in units of the lag time of the MSM.
    print "mfpts:", mfpts
    np.savetxt('mfpts_from_i_to_j.txt', np.array(mfpts))
    total_flux = np.sum(paths[1])
    print "total_flux:", total_flux
    sort = np.argsort(pfold)
    total_line_width = np.sum(paths[1][0:5])
    # top 5 paths, to get all paths set this number higher
    for j in range(5):
        print "path:", paths[0][j]
        print "flux:", paths[1][j], paths[1][j] / float(np.sum(paths[1]))
        x = []
        for k in range(len(paths[0][j])):
            x.extend(np.where(np.arange(100)[sort] == paths[0][j][k])[0])
        plt.plot(x,
                 pfold[paths[0][j]],
                 linewidth=np.log(paths[1][j] / float(total_line_width)))
    plt.legend(['%1.8f' % i for i in paths[1][0:5]],
               fontsize=18,
               loc='upper left')
    for i in range(len(pfold)):
        plt.plot(i, pfold[sort[i]], 'o')
        plt.text(i, pfold[sort[i]], sort[i])
    plt.savefig('pfold_ev%d_0.01.png' % ev_id)
Example #7
0
from sklearn.externals import joblib

ids = range(6383, 6391)

for p_id in ids:

    msm = joblib.load(
        'MSMs-{pid}-macro40/MSMs-{pid}-macro40.pkl'.format(pid=p_id))
    committors = tpt.committors(sources=[4], sinks=[13], msm=msm)
    net_fluxes = tpt.net_fluxes(sources=[4],
                                sinks=[13],
                                msm=msm,
                                for_committors=committors)
    top_10_paths_sub, top_10_fluxes_sub = tpt.paths(sources=[4],
                                                    sinks=[13],
                                                    net_flux=net_fluxes,
                                                    num_paths=10,
                                                    remove_path='subtract')
    top_10_paths_bot, top_10_fluxes_bot = tpt.paths(sources=[4],
                                                    sinks=[13],
                                                    net_flux=net_fluxes,
                                                    num_paths=10,
                                                    remove_path='bottleneck')
    output_dir = "Data-{pid}-macro40".format(pid=p_id)
    print top_10_paths_sub, top_10_fluxes_sub
    print top_10_paths_bot, top_10_fluxes_bot

    fn_committors = os.path.join(output_dir, "committors.npy")
    fn_n_fluxes = os.path.join(output_dir, "net_Fluxes.mtx")
    fn_10_paths_sub = os.path.join(output_dir, "top_paths_substract.npy")
    fn_10_fluxes_sub = os.path.join(output_dir, "top_fluxes_substract.npy")
Example #8
0
def plot_tpaths(msm,
                sources,
                sinks,
                for_committors=None,
                num_paths=1,
                pos=None,
                node_size=None,
                node_color='pomegranate',
                edge_color='carbon',
                alpha=.7,
                with_labels=True,
                ax=None,
                **kwargs):
    """
    Plot TPT network diagram.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    sources : int or list, optional
        TPT source states
    sinks : int or list, optional
        TPT sink states
    sinks : ndarray, optional
        Pre-computed forward committors
    pos : dict, optional
        Node positions in dict format (e.g. {node_id : [x, y]})
    node_color : str or [r, g, b], optional
        networkx node colors
    node_size : int or list, optional
        networkx node size
    node_color : str, optional
        networkx edge color
    alpha : float, optional  (default: 0.7)
        Opacity of nodes
    ax : matplotlib axis, optional (default: None)
        Axis to plot on, otherwise uses current axis.
    with_labels : boolean, optional
        Whether or not to include node labels (default: True)
    **kwargs : dict, optional
        Extra arguments to pass to networkx.draw_networkx

    Returns
    -------
    ax : Axis
        matplotlib figure axis

    """
    if hasattr(msm, 'all_populations_'):
        pop = msm.all_populations_.mean(0)
    elif hasattr(msm, 'populations_'):
        pop = msm.populations_

    net_flux = tpt.net_fluxes(sources,
                              sinks,
                              msm,
                              for_committors=for_committors)
    paths, _ = tpt.paths(sources, sinks, net_flux, num_paths=num_paths)

    graph = nx.DiGraph()
    for path in paths:
        for u, v in zip(path[:-1], path[1:]):
            graph.add_edge(u, v, weight=net_flux[u, v])

    if not ax:
        ax = pp.gca()

    if pos is None:
        pos = nx.spring_layout(graph)

    if node_size is None:
        node_size = 5000. * pop

    if isinstance(node_size, (list, np.ndarray)):
        node_size = [node_size[i] for i in graph.nodes()]

    if isinstance(node_color, (list, np.ndarray)):
        node_color = [node_color[i] for i in graph.nodes()]

    nx.draw_networkx(graph,
                     pos=pos,
                     node_color=node_color,
                     alpha=alpha,
                     node_size=node_size,
                     edge_color=edge_color,
                     ax=ax,
                     with_labels=with_labels,
                     **kwargs)

    return ax
Example #9
0
ax = msme.plot_tpaths(msm, start_ind[0], [pop_ind], pos=pos)
plt.tight_layout()
plt.savefig('tpath.eps')
plt.clf()

ax = msme.plot_tpaths(msm, start_ind[0], [pop_ind], pos=pos13)
plt.tight_layout()
plt.savefig('tpath_13.eps')
plt.clf()


net_flux_matrix = net_fluxes(start_ind[0], [pop_ind], msm)

flux_matrix = fluxes(start_ind[0], [pop_ind], msm)

paths_list, fluxes1 = paths(start_ind[0], [pop_ind], net_flux_matrix)

paths_list_d, fluxes1_d = paths(start_ind[0], [pop_ind], net_flux_matrix, remove_path='bottleneck')


print('num states in path 1', len(paths_list[0]))

test_3 = np.unique(np.concatenate((paths_list[0],paths_list[1], paths_list[2]), 0))
test_5 = np.unique(np.concatenate((paths_list[0],paths_list[1], paths_list[2], paths_list[3], paths_list[4]), 0))

test_3d = np.unique(np.concatenate((paths_list_d[0],paths_list_d[1], paths_list_d[2]), 0))
test_5d = np.unique(np.concatenate((paths_list_d[0],paths_list_d[1], paths_list_d[2], paths_list_d[3], paths_list_d[4]), 0))

tot_flux = fluxes1.sum()

print('sum of fluxes is ', tot_flux)
Example #10
0
def plot_tpaths(msm,
                sources,
                sinks,
                for_committors=None,
                num_paths=1,
                pos=None,
                node_color='pomegranate',
                edge_color='carbon',
                ax=None,
                **kwargs):
    """
    Plot TPT network diagram.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    sources : int or list, optional
        TPT source states
    sinks : int or list, optional
        TPT sink states
    sinks : ndarray, optional
        Pre-computed forward committors
    pos : dict, optional
        Node positions in dict format (e.g. {node_id : [x, y]})
    node_color : str or [r, g, b], optional
        networkx node colors
    node_size : int, optional
        networkx node size
    node_size : str or [r, g, b], optional
        networkx edge color
    ax : matplotlib axis, optional (default: None)
        Axis to plot on, otherwise uses current axis.
    with_labels : boolean, optional
        Whether or not to include node labels (default: True)
    **kwargs : dict, optional
        Extra arguments to pass to networkx.draw_networkx

    Returns
    -------
    ax : Axis
        matplotlib figure axis

    """
    net_flux = tpt.net_fluxes(sources,
                              sinks,
                              msm,
                              for_committors=for_committors)
    paths, _ = tpt.paths(sources, sinks, net_flux, num_paths=num_paths)

    graph = nx.DiGraph()
    for path in paths:
        for u, v in zip(path[:-1], path[1:]):
            graph.add_edge(u, v, weight=net_flux[u, v])

    if not ax:
        ax = pp.gca()

    if not pos:
        pos = nx.spring_layout(graph)

    nx.draw_networkx(graph,
                     pos=pos,
                     node_color=node_color,
                     edge_color=edge_color,
                     ax=ax,
                     **kwargs)

    return ax