Exemple #1
0
def main():
    # compute data
    bas_syst = generate_basic_system()
    fno_syst = add_fourth_node(bas_syst, emb_syst)
    assert (emb_syst.jacobian[:3, :3] == fno_syst.jacobian[:3, :3]).all()

    bas_mats, bas_extra = simulate(bas_syst, 100)
    fno_mats, fno_extra = simulate(fno_syst, 100)
    emb_mats, emb_extra = simulate(emb_syst, 100)

    # generate plot
    plt.figure(figsize=(20, 6))
    gs = gridspec.GridSpec(2, 3, width_ratios=[2, 4, 2])

    plot_system(fno_extra[0], plt.subplot(gs[0, 0]))
    plot_system(emb_extra[0], plt.subplot(gs[1, 0]))

    plot_solution(fno_extra[1], plt.subplot(gs[0, 1]))
    plot_solution(emb_extra[1], plt.subplot(gs[1, 1]))

    plot_correlation_hist(fno_mats, plt.subplot(gs[0, 2]))
    plot_correlation_hist(emb_mats, plt.subplot(gs[1, 2]))

    plot_correlation_hist(bas_mats, plt.subplot(gs[0, 2]), shade=True)
    plot_correlation_hist(bas_mats, plt.subplot(gs[1, 2]), shade=True)

    plt.tight_layout()
    plt.savefig('images/embedded_motif.pdf')
Exemple #2
0
def configuration_overview(func, fname, draw_all=True):
    fig = plt.figure()
    gs = gridspec.GridSpec(3, 5, width_ratios=[1,.2,1,1,1])

    for i, conf in enumerate([(1,1), (4,2), (2,1)]):
        syst = generate_basic_system(*conf)
        func(syst, plt.subplot(gs[i, 0]))

        if draw_all:
            for j, m in enumerate(add_node_to_system(syst)[3:6]):
                func(m, plt.subplot(gs[i, j+2]))

    if draw_all:
        fig.text(0.5, 0.04, 'varied embedding', ha='center', fontsize=20)
    fig.text(0.085, 0.5, 'varied parameters', va='center', rotation='vertical', fontsize=20)

    plt.savefig('presentation/images/overview_{}.pdf'.format(fname))
Exemple #3
0
def single_corr_coeff_hist(reps=5000):
    """ Plot distribution of single correlation coefficients
    """
    def do(syst, ax):
        # data
        single_run_matrices = []
        for _ in trange(reps):
            sol = solve_system(syst)

            sol_extract = sol.T[int(len(sol.T)*3/4):]
            single_run_mat = compute_correlation_matrix(np.array([sol_extract]))

            if single_run_mat.shape == (4, 4):
                single_run_mat = single_run_mat[:-1,:-1]
            assert single_run_mat.shape == (3, 3)

            single_run_matrices.append(single_run_mat)
        single_run_matrices = np.asarray(single_run_matrices)

        # plotting
        cols = cycle(['b', 'r', 'g', 'c', 'm', 'y', 'k'])
        for i, row in enumerate(single_run_matrices.T):
            for j, series in enumerate(row):
                if i == j: break
                plot_histogram(
                    series[series!=1], ax,
                    label=r'$c_{{{},{}}}$'.format(i,j),
                    facecolor=next(cols), alpha=0.5,
                    bins=100)

    # data
    syst = generate_basic_system()
    more = add_node_to_system(syst)[::10]
    print('#more', len(more))

    # plot
    f, axes = plt.subplots(len(more), 2, figsize=(9,20))

    do(syst, axes[0,0]); print()
    for i, m in tqdm(enumerate(more), total=len(more)):
        if i > 0:
            plot_system(m, axes[i,0])
        do(m, axes[i,1])

    plt.tight_layout()
    save_figure('images/correlation_distribution.pdf', bbox_inches='tight')
Exemple #4
0
    def test_run(self):
        steuer_syst = generate_basic_system()
        steuer_syst.fluctuation_vector = np.array([1e-5, 0, 0]) # reduce randomness

        syst, mat, sol = analyze_system(
            steuer_syst,
            repetition_num=100,
            use_ode_sde_diff=False)

        self.assertEqual(steuer_syst, syst)

        npt.assert_allclose(sol[0][-1], 2.5, atol=0.1)
        npt.assert_allclose(sol[1][-1], 1.25, atol=0.1)
        npt.assert_allclose(sol[2][-1], 5., atol=0.1)

        npt.assert_allclose(mat, np.array([
            [1, 0.7, 0.47],
            [0.7, 1, 0.87],
            [0.47, 0.87, 1]
        ]), atol=0.3)
Exemple #5
0
    def do(gs, res):
        param_range = np.linspace(.1, 5, res)
        currow = 0
        for k_m in tqdm(param_range):
            for k_23 in tqdm(param_range):
                syst = generate_basic_system(k_m=k_m, k_23=k_23)

                single_run_matrices = []
                for r in trange(reps):
                    _,mat,sol = analyze_system(syst, repetition_num=1)
                    if mat is None:
                        continue

                    sol_extract = sol.T[int(len(sol.T)*3/4):]

                    if r == 0:
                        plot_system_evolution(
                            sol_extract.T,
                            plt.subplot(gs[currow,2]), show_legend=False)

                    single_run_mat = compute_correlation_matrix(np.array([sol_extract]))

                    if single_run_mat.shape == (4, 4):
                        single_run_mat = single_run_mat[:-1,:-1]
                    assert single_run_mat.shape == (3, 3)

                    single_run_matrices.append(single_run_mat)

                plot_system(syst, plt.subplot(gs[currow,0]))

                single_run_matrices = np.asarray(single_run_matrices)
                for i, row in enumerate(single_run_matrices.T):
                    for j, series in enumerate(row):
                        if i == j: break

                        ax = plt.subplot(gs[currow,1])
                        sns.distplot(series, ax=ax, label=r'$c_{{{},{}}}$'.format(i,j))
                        ax.set_xlim((-1,1))

                currow += 1
Exemple #6
0
def lyapunov_equation():
    """ Check if our experiments satisfy the lyapunov equation
    """
    # create systems
    sde_system = generate_basic_system()
    sde_system.fluctuation_vector[-1] = 2

    ode_system = copy.deepcopy(sde_system)
    ode_system.fluctuation_vector = np.zeros(sde_system.fluctuation_vector.shape)

    # generate data
    sde_sol = solve_system(sde_system)
    ode_sol = solve_system(ode_system)

    sol = ode_sol - sde_sol
    sol_extract = sol.T[int(len(sol.T)*3/4):] # extract steady-state

    # investigate result
    J = sde_system.jacobian
    C = np.cov(sol_extract.T)
    D = np.diag(sde_system.fluctuation_vector)

    term1 = J @ C + C @ J.T
    term2 = -2 * D

    print(term1, '\n',term2)

    # plot stuff
    #plt.plot(sol_extract)
    plt.scatter(term1.ravel(), term2.ravel())

    plt.title(f'Fluctuation vector: {sde_system.fluctuation_vector}')
    plt.xlabel('J @ C + C @ J.T')
    plt.ylabel('-2 * D')

    plt.savefig('images/lyapunov_equation.pdf')
Exemple #7
0
def check_ergodicity(reps=500):
    """ Check whether simulated systems are ergodic
    """
    def get_matrices(syst, entry_num=100):
        """ Get correlation matrices for both cases
        """
        # multiple entries from single run
        single_run_matrices = []
        for _ in range(entry_num):
            sol = solve_system(syst)

            extract = sol.T[-entry_num:]
            single_run_mat = compute_correlation_matrix(np.array([extract]))

            single_run_matrices.append(single_run_mat)
        avg_single_mat = np.mean(single_run_matrices, axis=0)

        # one entry from multiple runs
        multiple_runs = []
        for _ in range(entry_num):
            sol = solve_system(syst)

            extract = sol.T[-1].T
            multiple_runs.append(extract)
        multiple_mat = compute_correlation_matrix(np.array([multiple_runs]))

        return avg_single_mat, multiple_mat

    syst = generate_basic_system()

    single_runs = []
    multiple_runs = []
    for _ in trange(reps):
        sm, rm = get_matrices(syst)

        single_runs.append(sm)
        multiple_runs.append(rm)
    single_runs = np.array(single_runs)
    multiple_runs = np.array(multiple_runs)

    # plot result
    dim = syst.jacobian.shape[1]

    plt.figure(figsize=(6, 14))
    gs = mpl.gridspec.GridSpec(int((dim**2-dim)/2), 1)

    axc = 0
    for i in range(dim):
        for j in range(dim):
            if i == j: break
            ax = plt.subplot(gs[axc])

            plot_histogram(
                single_runs[:,i,j], ax,
                alpha=0.5,
                label='Multiple entries from single run')
            plot_histogram(multiple_runs[:,i,j], ax,
                facecolor='mediumturquoise', alpha=0.5,
                label='One entry from multiple runs')

            ax.set_title('Nodes {}, {}'.format(i, j))
            ax.set_xlabel('correlation')
            ax.legend(loc='best')

            axc += 1

    plt.tight_layout()
    plt.savefig('images/ergodicity_check.pdf')
Exemple #8
0
def detailed_system():
    syst = generate_basic_system()

    plt.figure()
    plot_system(syst, plt.gca())
    plt.savefig('presentation/images/FFL.pdf', dpi=300)
Exemple #9
0
def check_ergodicity(reps=500):
    """ Check whether simulated systems are ergodic
    """
    def get_matrices(syst, entry_num=100):
        """ Get correlation matrices for both cases
        """
        # multiple entries from single run
        single_run_matrices = []
        for _ in range(entry_num):
            sol = solve_system(syst)

            extract = sol.T[-entry_num:]
            single_run_mat = compute_correlation_matrix(np.array([extract]))

            single_run_matrices.append(single_run_mat)
        avg_single_mat = np.mean(single_run_matrices, axis=0)

        # one entry from multiple runs
        multiple_runs = []
        for _ in range(entry_num):
            sol = solve_system(syst)

            extract = sol.T[-1].T
            multiple_runs.append(extract)
        multiple_mat = compute_correlation_matrix(np.array([multiple_runs]))

        return avg_single_mat, multiple_mat

    syst = generate_basic_system()

    single_runs = []
    multiple_runs = []
    for _ in trange(reps):
        sm, rm = get_matrices(syst)

        single_runs.append(sm)
        multiple_runs.append(rm)
    single_runs = np.array(single_runs)
    multiple_runs = np.array(multiple_runs)

    # plot result
    dim = syst.jacobian.shape[1]

    plt.figure(figsize=(6, 14))
    gs = mpl.gridspec.GridSpec(int((dim**2-dim)/2), 1)

    axc = 0
    for i in range(dim):
        for j in range(dim):
            if i == j: break
            ax = plt.subplot(gs[axc])

            plot_histogram(
                single_runs[:,i,j], ax,
                alpha=0.5,
                label='Multiple entries from single run')
            plot_histogram(multiple_runs[:,i,j], ax,
                facecolor='mediumturquoise', alpha=0.5,
                label='One entry from multiple runs')

            ax.set_title('Nodes {}, {}'.format(i, j))
            ax.set_xlabel('correlation')
            ax.legend(loc='best')

            axc += 1

    plt.tight_layout()
    plt.savefig('images/ergodicity_check.pdf')
Exemple #10
0
def visualize_node_influence():
    """ Compare examples where fourth node perturbs system and where it doesn't
    """
    def simulate(syst, reps=1000):
        matrices = []
        with tqdm(total=reps) as pbar:
            while reps >= 0:
                _, mat, _ = analyze_system(syst, repetition_num=1)
                if mat is None:
                    continue
                pbar.update()
                reps -= 1

                if mat.shape == (4, 4):
                    mat = mat[:-1, :-1]
                assert mat.shape == (3, 3)

                matrices.append(mat)
        return np.asarray(matrices)

    def plot_correlation_hist(matrices, ax):
        for i, row in enumerate(matrices.T):
            for j, series in enumerate(row):
                if i == j: break

                sns.distplot(series,
                             ax=ax,
                             label=r'$c_{{{},{}}}$'.format(i, j))

        ax.set_xlabel('correlation')
        ax.set_ylabel('count')
        ax.set_xlim((-1, 1))
        ax.legend(loc='best')

    def plot_system(syst, ax):
        graph = nx.from_numpy_matrix(syst.jacobian.T,
                                     create_using=nx.DiGraph())
        nx.draw(graph, ax=ax, with_labels=True)
        ax.axis('off')
        ax.set_xticks([], [])
        ax.set_yticks([], [])

    # generate systems
    basic_system = generate_basic_system()
    more_systs = add_node_to_system(basic_system)

    similar_system = more_systs[42]
    different_system = more_systs[22]  # 52

    systems = {
        'basic': basic_system,
        'similar': similar_system,
        'different': different_system
    }

    # simulations
    matrices = {}
    for name, syst in systems.items():
        matrices[name] = (syst, simulate(syst))

    # plot result
    for name, (syst, mats) in matrices.items():
        plt.figure()
        plot_correlation_hist(mats, plt.gca())
        plot_system(syst, plt.axes([.3, .5, .3, .3]))
        plt.savefig(f'images/node_influence_{name}.pdf')