Mike5298
Mike5298

Reputation: 385

Why is my python repeat function not working?

Im trying to run a function that contains a stochastic simulation x multiple times. The first thing I've tried is to write a second function which contains a for loop to call the first function x times.

def repeat_func(start_state, LHS, stoch_rate, state_change_array):        
    """ A function to call the gillespie_tau_leaping x amount of times."""
    for i in range(10):
        popul_num_all, tao_all = gillespie_tau_leaping(start_state, LHS, stoch_rate, state_change_array)
    return popul_num_all, tao_all

I want to plot popul_num_all and tao_all on a graph x times. These are two arrays which are the returned objects from the gillespie_tau_leaping function. popul_num_all shows the changing molecule numbers (wants to be on the y-axis) and tao_all is the change in time as the simulation runs (wants to be on the x-axis).

Heres the code I'm using to produce the plots:

def gillespie_plot(tao_all, popul_num_all):
    fig, ax = plt.subplots()
    for i, label in enumerate(['Enzyme', 'Substrate', 'Enzyme-Substrate complex', 'Product']):
        ax.plot(tao_all, popul_num_all[:, i], label=label)
    ax.legend()
    plt.show()
    return fig

But in this current form the simulation only runs once and only one graph is plotted.

I know there are quite a few similar questions that are for things like recursion and lambda functions, but I can't get those solutions to work in my program.

Where am I going wrong?

Cheers

Upvotes: 0

Views: 182

Answers (1)

Aparna
Aparna

Reputation: 422

The "repeat_func" written by you returns popul_num_all and tao_all. The reason why you are getting a single value for popul_num_all and tao_all is as explained below:

When i = 1, popul_num_all, tao_all = some array returned by gillespie_tau_leaping(). When i = 2, popul_num_all, tao_all = again an array returned by gillespie_tau_leaping(). So during every iteration, the variables popul_num_all, tao_all are updated and thus when you return these variables in "repeat_func", it returns the values during the last iteration only. If you want to plot the graph during every iteration of for loop, then call the gillespie_plot function inside the loop.

Also, you are passing the same inputs to gillespie_tau_leaping() inside the for loop and hence even if you try to plot for all iterations the graphs will be similar.

Upvotes: 2

Related Questions