EmJ
EmJ

Reputation: 49

Why isn't += adding to the variable's value?

I am using solve_ivp & the generalized Lotka-Volterra equation to calculate changes in species' populations over time. In the code, the equation is split into two parts as shown below:


species = ['fox','rabbits','deer']

t = np.linspace(0, 10, 50)
first_ABC = solve_ivp(ecoNetwork, (0, 10), X0,  t_eval = t, args=(interactionStrength, growthRate), method = 'RK23')

def ecoNetwork(t, X, interactionStrength, growthRate):
    # define new array to return
    output_array = []
    # loop through all the species
    for outer_index, outer_species in enumerate(species): 
        # grab one set of growth rates at a time
        amount = growthRate[outer_species] * X[outer_index]
        for inner_index, inner_species in enumerate(species):
            # grab one set of interaction matrices at a time
            amount += (interactionStrength[outer_species][inner_species] * X[outer_index] * X[inner_index]) 
        # append values to output_array
        output_array.append(amount)
    # return array
    return output_array

However, the "amount +=" part of the code is not working as expected and doesn't seem to be adding the second part of the equation to the first. It works if I change the line to a new variable name, e.g.

amount2 = amount + (interactionStrength[outer_species][inner_species] * X[outer_index] * X[inner_index]) 

Can someone explain why the += isn't working?

X0 and growthRates are both pandas dataframes and the interaction matrix is formatted like this:

                fox   rabbit         deer 
fox          0.000000  -1           0.000000 
rabbit       1         0.000000     0.000000 
deer         0.000000  0.000000     0.000000 

Upvotes: 1

Views: 77

Answers (2)

Dude
Dude

Reputation: 345

Python variables store references to objects instead of their values. Therefore, either you will need to use another variable (as in your case amount2) or use "copy" module to create a shallow copy of amount. (cleaner solution)

https://docs.python.org/2/library/copy.html

Upvotes: 0

Jesper
Jesper

Reputation: 1649

I can't really say why += is not working, but it's a special operator that would have to be defined in the class of the specific data type stored in amount.

If you say that

amount2 = amount + (interactionStrength[outer_species][inner_species] * X[outer_index] * X[inner_index]) 

works, then I would believe that

amount = amount + (interactionStrength[outer_species][inner_species] * X[outer_index] * X[inner_index]) 

would do exactly what you want.

Upvotes: 1

Related Questions