Exemplo n.º 1
0
def nextFrame(arg):

    """ Function called for each successive animation frame; arg is the frame number """

    global mmax, pmax, ADs, ADList, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth
    global fixed, p, BurnIn, t, num_sims, width, height, Rates, GrowthDict, RD
    global DispDict, MaintDict, gmax, dmax, maintmax, IndIDs, Qs, EVList
    global IndID, IndX, IndY, Ind_scatImage, SpeciesIDs, TLList
    global RX, RY, RID, RIDs, RVals, EnvD, resource_scatImage, Mu, Maint
    global seedCom, m, r, sim
    global N, ct, RDens, RDiv, RRich, T, R, LowerLimit, prod_i, prod_q
    global Ts, Rs, PRODIs, Ns, RDENs, RDIVs, RRICHs, GrowthList, MaintList, RList
    global MUs, MAINTs, PRODNs, PRODPs, PRODCs, Gs, Ms, Ds
    global DispList, envgrads, MainFactorDict, RPFDict, enzyme_field, u0

    global TrophicComplexityLevel, SpatialComplexityLevel, encList, std
    global ResourceComplexityLevel, BiologicalComplexityLevel
    global Ragg, Iagg, static, Deadlist

    numDead = 0
    ct += 1
    #print ct

    encounters = 0
    # Inflow of resources
    RList, RVals, RX, RY,  RIDs, RID = bide.ResIn(std, ct, RList, RVals, RX, RY,  RID,\
    RIDs, r, width, height, u0, TrophicComplexityLevel, SpatialComplexityLevel, \
    ResourceComplexityLevel, BiologicalComplexityLevel)

    # Immigration
    SpeciesIDs, IndX, IndY,  MaintDict, MainFactorDict, RPFDict, EnvD, GrowthDict,\
    DispDict, IndIDs, IndID, Qs, RD, GrowthList, MaintList, DispList, ADList, EVList,\
    TLList = bide.immigration(std, mmax, pmax, dmax, gmax, maintmax, seedCom, m, \
    SpeciesIDs, IndX, IndY, width, height, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads,\
    GrowthDict, DispDict, IndIDs, IndID, Qs, RD, u0, GrowthList, MaintList, \
    DispList, ADList, EVList, TLList, ct, TrophicComplexityLevel, \
    SpatialComplexityLevel, ResourceComplexityLevel, BiologicalComplexityLevel)

    # Dispersal
    if SpatialComplexityLevel < 3:
        SpeciesIDs, Qs, IndIDs, ID, IndX, IndY, GrowthDict, DispDict, GrowthList, \
        MaintList, DispList, ADList, EVList, TLList, RList, RVals, RX, RY, RIDs, RID, numDead = bide.dispersal(SpeciesIDs,\
	Qs, IndIDs, IndID, IndX, IndY, width, height, GrowthDict, \
        DispDict, RD, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, \
        GrowthList, MaintList, DispList, ADList, EVList, TLList, RList, RVals, RX, RY, RIDs, RID, TrophicComplexityLevel, \
        SpatialComplexityLevel, ResourceComplexityLevel, BiologicalComplexityLevel, numDead)

    elif SpatialComplexityLevel == 3:
        RList, RVals, RIDs, RID, RX, RY, SpeciesIDs, Qs, IndIDs, IndID, IndX, IndY, width, height, GD, RD, DispD, GrowthList,\
        MaintList, DispList, ADList, TLList, EVList, numDead = bide.chemotaxis(RList, RVals, RIDs, RID, RX, RY, SpeciesIDs, Qs, IndIDs, IndID,\
        IndX, IndY, width, height, GrowthDict, RD, DispDict, GrowthList, MaintList, DispList, ADList, TLList, EVList,\
        TrophicComplexityLevel, SpatialComplexityLevel, ResourceComplexityLevel, BiologicalComplexityLevel, numDead)

    # Resource Dispersal
    if SpatialComplexityLevel == 1:
        RList, RVals, RX, RY, RID, RIDs = bide.res_dispersal(ct, RList, RVals, RX, RY, RID, RIDs, r,\
        width, height, u0, TrophicComplexityLevel, SpatialComplexityLevel, \
        ResourceComplexityLevel, BiologicalComplexityLevel)

    PRODI = 0
    p1 = len(Qs)

    # Consume
    RList, RVals, RIDs, RID, RX, RY, SpeciesIDs, Qs, encounters = bide.consume(enzyme_field, \
    RList, RVals, RIDs, RID, RX, RY, SpeciesIDs, Qs, IndIDs, IndID, IndX, IndY, \
    width, height, GrowthDict, MaintDict, RD, DispDict, GrowthList, MaintList, DispList, ADList, \
    TLList, EVList, TrophicComplexityLevel, SpatialComplexityLevel, \
    ResourceComplexityLevel, BiologicalComplexityLevel)

    # Reproduction
    SpeciesIDs, Qs, IndIDs, ID, IndX, IndY, GrowthDict, DispDict, GrowthList, MaintList, \
    DispList, ADList, EVList, TLList, RList, RVals, RX, RY, RID, RIDs, numDead = bide.reproduce(SpeciesIDs, Qs, IndIDs, IndID, \
    IndX, IndY,  width, height, GrowthDict, DispDict, RD, MaintDict, MainFactorDict, \
    RPFDict, EnvD, envgrads, GrowthList, MaintList, DispList, ADList, EVList, TLList, RList, RVals, RX, RY, RID, RIDs, \
    TrophicComplexityLevel, SpatialComplexityLevel, ResourceComplexityLevel, \
    BiologicalComplexityLevel, numDead)

    # maintenance
    SpeciesIDs, IndX, IndY, IndIDs, Qs, GrowthList, MaintList, DispList, ADList,\
    EVList, TLList, RList, RVals, RX, RY, RIDs, RID, numDead = bide.maintenance(SpeciesIDs, IndX, IndY, MaintDict, MainFactorDict, \
    RPFDict, EnvD, IndIDs, Qs, GrowthList, MaintList, DispList, ADList, EVList, TLList, RList, RVals, RX, RY, RIDs, RID,\
    TrophicComplexityLevel, SpatialComplexityLevel, ResourceComplexityLevel, \
    BiologicalComplexityLevel, numDead)

    # transition to or from dormancy
    SpeciesIDs, IndX, IndY, GrowthList, DispList, ADList, EVList, IndIDs, Qs, GrowthList, \
    MaintList, TLList, RList, RVals, RX, RY, RIDs, RID, numDead = bide.transition(SpeciesIDs, IndX, IndY, GrowthList, DispList, ADList, EVList,\
    IndIDs, Qs, MaintList, TLList, RList, RVals, RX, RY, RIDs, RID, MainFactorDict, RPFDict, \
    TrophicComplexityLevel, SpatialComplexityLevel, ResourceComplexityLevel, \
    BiologicalComplexityLevel, numDead)

    p2 = len(Qs)
    PRODI = p2 - p1

    ax1 = fig.add_subplot(2,2,1) # initiate 1st plot
    ax2 = fig.add_subplot(2,2,2) # initiate 2nd plot
    ax3 = fig.add_subplot(2,2,3) # initiate 3rd plot
    ax4 = fig.add_subplot(2,2,4) # initiate 4th plot

    plt.tick_params(axis='both', which='both', bottom='off', top='off', \
        left='off', right='off', labelbottom='off', labelleft='off')

    N = len(IndIDs)

    if N == 0 or N > 20000:

        TrophicComplexityLevel = choice([1,2,3]) #
        SpatialComplexityLevel = choice([1,2,3]) # goes up to 3
        ResourceComplexityLevel = choice([1,2,3]) # goes up to 3 but needs enzyme breakdown
        BiologicalComplexityLevel = 2

        RDens, RDiv, RRich, Mu, Maint, ct, IndID, RID, N, T, R, PRODI, PRODQ = [0]*13
        ADList, ADs, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth, GrowthList, MaintList, RVals, \
        DispList, EVList, TLList = [list([]) for _ in xrange(12)]

        SpeciesIDs, IndX, IndY, IndIDs, Qs, RX, RY, RIDs, RList, RVals, Gs, Ms, \
        Ds, Rs, PRODIs, Ns, RDENs, RDIVs, RRICHs, MUs, MAINTs, encList, Ragg, Iagg = [list([]) for _ in xrange(24)]
        
        if u0 == max(Rates):
            #sim += 1

            width, height, seedCom, m, r, gmax, maintmax, dmax, envgrads, Rates, pmax, mmax, std = rp.get_rand_params(fixed)

            GrowthDict, MaintDict, MainFactorDict, RPFDict, EnvD, RD, DispDict,\
            EnvD = {}, {}, {}, {}, {}, {}, {}, {}

            enzyme_field = [0]*(width*height)

        p = 0
        BurnIn = 'not done'

    Ns.append(N)
    rr = len(RIDs)
    numD = ADList.count('d')

    pD = 0.0
    if N > 0:
        pD = round((numD/N*100), 2)

    Title = ['Active individuals (red) consume resources, grow, reproduce, go dormant (gray) and die in complex resource-limited environment.\n \
Resource complexity: ' + str(ResourceComplexityLevel) + ',  Trophic complexity: ' + str(TrophicComplexityLevel) + ',  \
Spatial complexity: ' + str(SpatialComplexityLevel) + '     N: '+str(N)+',  Resources: '+str(rr)+',  ct: '+str(ct)+ ', \
%Dormant: '+str(pD) + '\n# of inflowing resources: ' + str(r) + ', Aggregation: ' + str(round(std,2))]

    txt.set_text(' '.join(Title))
    #ax1.set_ylim(0, height)
    #ax1.set_xlim(0, width)

    plot_system = 'yes'
    if plot_system == 'yes':

        ##### PLOTTING THE SYSTEM ##############################################
        resource_scatImage.remove()
        Ind_scatImage.remove()
        plot2.remove()
        plot3.remove()
        plot4.remove()
        
        colorlist = []

        ind_sizelist = []
        res_sizelist = []

        for val in RVals:
            res_sizelist.append(val*200)

        for i, val in enumerate(SpeciesIDs):
            if ADList[i] == 'a':
                colorlist.append('red')
            elif ADList[i] == 'd':
                colorlist.append('0.3')

            ind_sizelist.append(Qs[i] * 1000)


        resource_scatImage = ax1.scatter(RX, RY, s = res_sizelist, c = 'w',
                    edgecolor = 'SpringGreen', lw = 2.0, alpha=0.7)

        Ind_scatImage = ax1.scatter(IndX, IndY, s = ind_sizelist, c = colorlist,
                    edgecolor = '0.2', lw = 0.2, alpha=0.8)
                    
        ax2 = fig.add_subplot(2,2,2) # initiate 2nd plot
        ax3 = fig.add_subplot(2,2,3) # initiate 3rd plot
        ax4 = fig.add_subplot(2,2,4) # initiate 4th plot

        plot2 = ax2.scatter([0],[0], alpha=0)
        plot3 = ax3.scatter([0],[0], alpha=0)
        plot4 = ax4.scatter([0],[0], alpha=0)

    if len(Ns) >= 50:

        if BurnIn == 'not done':
            AugmentedDickeyFuller = sta.adfuller(Ns)
            val, p = AugmentedDickeyFuller[0:2]

            if p >= 0.05:
                Ns.pop(0)

            elif p < 0.05 or isnan(p) == True:
                BurnIn = 'done'
                Ns = [Ns[-1]] # only keep the most recent N value
                
    if ct == 100:
        BurnIn = 'done'
        Ns = [Ns[-1]] # only keep the most recent N value


    if BurnIn == 'done':

        PRODIs.append(PRODI)

        if len(RList) > 0:
            RDens = len(RList)/(height*width)

        RDENs.append(RDens)
        R = len(RX)
        Rs.append(R)
        encList.append(encounters)

        if N >= 1:

            if N >= 2:
                Imor = spatial.morisitas(IndX, IndY, width, height)
                Iagg.append(Imor)

            if R >= 1:
                q = min([20, R])

                #avg_dist1 = spatial.avg_dist(IndX, RX, IndY, RY, q)
                avg_dist2 = spatial.nearest_neighbor(IndX, RX, IndY, RY, q)
                AVG_DIST.append(avg_dist2)

                if R >= 2:
                    Rmor = spatial.morisitas(RX, RY, width, height)
                    Ragg.append(Rmor)

            spD = DispDict.values()
            spM = MaintDict.values()
            spG = GrowthDict.values()

            SpecDisp.append(mean(spD))
            SpecMaint.append(mean(spM))
            SpecGrowth.append(mean(spG))

            Gs.append(mean(GrowthList))
            Ms.append(mean(MaintList))
            Ds.append(mean(DispList))

            numD = ADList.count('d')
            ADs.append(numD/len(ADList))
            Deadlist.append(numDead)

        if len(Ns) >= 20:

            print '%4s' % sim, ' r:','%4s' %  r, ' R:','%4s' % int(round(mean(Rs))), ' N:','%5s' % int(round(mean(Ns))), \
            ' Dormant:', '%5s' % round(mean(ADs),3), ' Encounters:','%5s' % round(mean(encList),2), '   Spatial:', SpatialComplexityLevel, \
            'Resource:', ResourceComplexityLevel, 'Trophic:', TrophicComplexityLevel#, \
            #'Agg(I):', round(mean(Iagg), 2), 'Agg(R):', round(mean(Ragg),2)

            Rates = np.roll(Rates, -1, axis=0)
            u0 = Rates[0]

            if static == 'no':
                TrophicComplexityLevel = choice([1,2,3,4]) #
                SpatialComplexityLevel = choice([1,2,3]) # goes up to 3
                ResourceComplexityLevel = choice([1,2,3]) # goes up to 3 but needs enzyme breakdown
                BiologicalComplexityLevel = 2

            RDens, RDiv, RRich, Mu, Maint, ct, IndID, RID, N, T, R, PRODI, PRODQ, numD = [0]*14

            ADList, ADs, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth, GrowthList, MaintList, RVals, \
            DispList, EVList, TLList, Deadlist = [list([]) for _ in xrange(13)]

            SpeciesIDs, IndX, IndY, IndIDs, Qs, RX, RY, RIDs, RList, RVals, Gs, Ms, \
            Ds, Rs, PRODIs, Ns, RDENs, RDIVs, RRICHs, MUs, MAINTs, encList, Ragg, Iagg = [list([]) for _ in xrange(24)]

            p = 0
            BurnIn = 'not done'

            if u0 == max(Rates):
                sim += 1

                width, height, seedCom, m, r, gmax, maintmax, dmax, envgrads, Rates, pmax, mmax, std = rp.get_rand_params(fixed)

                GrowthDict, MaintDict, MainFactorDict, RPFDict, EnvD, RD, DispDict,\
                EnvD = {}, {}, {}, {}, {}, {}, {}, {}

                enzyme_field = [0]*(width*height)

            ####################### REPLACE ENVIRONMENT ########################
            ax1 = fig.add_subplot(2,2,1)
            ax2 = fig.add_subplot(2,2,2) # initiate first plot
            ax3 = fig.add_subplot(2,2,3) # initiate first plot
            ax4 = fig.add_subplot(2,2,4) # initiate first plot
Exemplo n.º 2
0
def Hbide(V, REStime, Rcons, Pcons, PropQ, time, mean, std, Kq, lgp, maint, res_pulse, im_pulse, env_noise, spatial_het, basic, system, disp_mu, disp_std):

    """
    V         :  Volume

    Rcons     :  resource concentration

    Pcons     :  propagule concentration

    maint     :  resource loss due to cell maintenance

    REStime   :  residence time

    time      :  number of time steps to run simulation. Needs to be large
    enough to allow the community to reach a relatively stable state

    dormancy  :  designate whether dormancy is allowed. If dormancy is True,
    then cell quotas of 0 result in dormancy, if dormancy = False, then cell
    quotas of 0 result in death and immediate 'removal'

    """

    r = V/REStime # rate of flow
    TR = Rcons * V # total resources in the local environment


    num_in = int(round(r * Pcons))
    if num_in < 1 and Pcons > 1:
        return ['Continuously empty system']

    Nlist = [] # total abundance
    Glist = [] # average growth rate
    Slist = []  # richness
    Prodlist = [] # productivity list
    Rlist = [] # total resources
    Qlist = [] # cell quota
    MAXUlist = []
    Tlist = [] # number of generations in the system
    MCT = []

    if basic == False:
        SoNlist = [] # average species abundance
        TOlist = [] # biomass turnover
        Evarlist = [] # evenness
        Hlist = [] # Shannon's diversity
        CTlist = [] # compositional turnover
        RADlist = [] # list of RADs

    maxUptake_list = []
    maxUptake_dict = {}

    xcoords =  []
    ycoords =  []
    zcoords =  []

    DispParamsDict = {}

    Qs1 = []
    Qs2 = list(Qs1)
    N = len(Qs1)

    Slist1 = []
    Slist2 = list(Slist1)

    inds1 = []
    inds2 = list(inds1)

    ID = 0
    lag = 0

    """ Initial bout of immigration """
    init_n = 1000
    Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, xcoords, ycoords, zcoords = bide.immigration(system, V, Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, mean, std, lgp, init_n, PropQ, xcoords, ycoords, zcoords, disp_mu, disp_std)

    Nlist2 = []
    pastBurnIn = 'no'

    Hurst = float()
    pval = float()

    for t in range(time):

        """ Resource resupply """
        TR += r * Rcons # Total Resources increase due to inflow

        """ Immigration """
        if system != 'ideal':
            Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, xcoords, ycoords, zcoords = bide.immigration(system, V, Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, mean, std, lgp, num_in, PropQ, xcoords, ycoords, zcoords, disp_mu, disp_std)


        """ Growth """
        Qs2, Slist2, inds2, maxUptake_list, Tlist, TR, glist, xcoords, ycoords, zcoords = bide.growth(Qs2, Slist2, inds2, maxUptake_list, Tlist, TR, Kq, maint, xcoords, ycoords, zcoords)

        N = len(Qs2)
        if N == 0:
            return ['N = 0']

        """ Reproduction """
        Qs2, Slist2, inds2, Tlist, maxUptake_list, Kq, ID, prod, xcoords, ycoords, zcoords = bide.reproduction(Qs2, Slist2, inds2, Tlist, maxUptake_list, Kq, ID, maint, xcoords, ycoords, zcoords)


        """ Check community variables and list lengths"""
        check = checks(Qs2, Slist2, inds2, Tlist, xcoords, ycoords, zcoords)
        if check[0] != 'pass':
            return check


        """ Emigration """ # will eventually be modified to allow individuals to naturally flow out
        Qs2, Slist2, inds2, Tlist, maxUptake_list, xcoords, ycoords, zcoords = bide.emigration(Qs2, Slist2, inds2, Tlist, maxUptake_list, r, V, xcoords, ycoords, zcoords, system)

        N = len(Qs2)
        if N == 0:
            return ['N = 0 after emigration']


        """ Dispersal """
        Qs2, Slist2, inds2, Tlist, maxUptake_list, DispParamsDict, Kq, ID, xcoords, ycoords, zcoords = bide.dispersal(V, Qs2, Slist2, inds2, Tlist, maxUptake_list, DispParamsDict, Kq, ID, xcoords, ycoords, zcoords, system)

        """ Outflow """
        TR, V = bide.outflow(TR, r, V)

        N = len(Qs2)
        if N == 0:
            return ['N = 0']


        if pastBurnIn == 'no':

            Nlist2.append(N)
            if len(Nlist2) > 500:

                Hurst, pval = timeSeries.get_burnin(Nlist2)
                if Hurst < 0.5 and pval < 0.01:
                    pastBurnIn = 'yes'
                    Nlist2 = []
                    burnIn = t
                    time += time # let the simulation go longer

                else:
                    pastBurnIn = 'no'


        if pastBurnIn == 'yes':

            """ Record community info """

            Glist.append(np.mean(glist))
            Nlist.append(prod)
            Slist.append(len(set(Slist2)))
            Prodlist.append(prod)
            Rlist.append(float(TR))
            Qlist.append(float(sum(Qs2)/len(Qs2)))
            MAXUlist.append(float(np.mean(maxUptake_list)))

            if min(Tlist) == 0 and max(Tlist) == 0:
                MCT.append(0)
            else:
                Tlist_noZeros = filter(lambda a: a != 0, Tlist)
                MCT.append(float(np.mean(Tlist_noZeros)))

            if basic == False:

                S1 = set(Slist1)
                s1 = len(S1)
                S2 = set(Slist2)
                s2 = len(S2)
                c = len(S1 & S2)
                CT = ((s1 - c) + (s2 - c))/np.mean([s1, s2])
                # Whittaker's tunover (species)

                I1 = set(inds1)
                i1 = len(I1)
                I2 = set(inds2)
                i2 = len(I2)
                c = len(I1 & I2)
                TO = ((i1 - c) + (i2 - c))/np.mean([i1, i2])
                # Whittaker's tunover (individuals)

                RAD = [] # Generate the rank-abundance distribution (RAD)
                for i in S2:
                    ab = Slist2.count(i)
                    RAD.append(ab)

                RAD.sort()
                RAD.reverse()

                RADtaulist = [10, 100, 1000]
                ct = RADtaulist.count(REStime)
                if ct > 0 and t == time-1:
                    RADlist = list([V, REStime, RAD])

                TOlist.append(TO)
                SoNlist.append(float(N/s2))

                Hlist.append(float(metrics.Shannons_even(RAD)))
                Evarlist.append(float(metrics.e_var(RAD)))
                CTlist.append(float(CT))


            if len(Nlist) >= 500:

                #lag = timeSeries.get_uncorrelated(Nlist)
                if REStime <= 10:
                    lag = 10
                else: lag = REStime

                if lag > 0:
                    samp_size = int(round(len(Nlist)/lag))

                    if samp_size >= 10:

                        Glist = sample(Glist, samp_size)
                        Nlist = sample(Nlist, samp_size)
                        Slist = sample(Slist, samp_size)
                        Prodlist = sample(Prodlist, samp_size)
                        MAXUlist = sample(MAXUlist, samp_size)
                        Rlist = sample(Rlist, samp_size)
                        Qlist = sample(Qlist, samp_size)
                        MCT = sample(MCT, samp_size)

                        if basic == True:
                            return [np.mean(Glist), np.mean(Nlist), np.mean(Slist),
                                    np.mean(Rlist), np.mean(Qlist), np.mean(MAXUlist),
                                    burnIn, lag, np.mean(Prodlist), np.mean(MCT),
                                    Hurst, pval]

                        elif basic == False:
                            TOlist = sample(TOlist, samp_size)
                            SoNlist = sample(SoNlist, samp_size)
                            Hlist = sample(Hlist, samp_size)
                            Evarlist = sample(Evarlist, samp_size)
                            CTlist = sample(CTlist, samp_size)

                            return [np.mean(Glist), np.mean(Nlist), np.mean(Rlist), np.mean(TOlist),
                                    np.mean(Qlist), np.mean(CTlist),
                                    np.mean(Evarlist), np.mean(Hlist), RADlist,
                                    np.mean(SoNlist), np.mean(MAXUlist), burnIn,
                                    lag, np.mean(Prodlist), np.mean(MCT), Hurst, pval]


        """ saving this generations lists """
        Slist1 = list(Slist2)
        inds1 = list(inds2)
        Qs1 = list(Qs2)

        if t == time-1 and pastBurnIn == 'no':
            return ['failed to reach stationarity in '+str(time)+' generations, H = '+str(round(Hurst, 3))+', p = '+str(round(pval, 3))]


    #lag = timeSeries.get_uncorrelated(Nlist)
    if REStime <= 10:
        lag = 10
    else: lag = REStime


    if lag == 0:
        return ['no sufficient time lag in '+str(len(Nlist))+' generations']

    else:
        samp_size = int(round(len(Nlist)/lag))
        if samp_size < 10:
            return ['insufficient sample of unbiased time points from '+str(len(Nlist))+' generations']

        Glist = sample(Glist, samp_size)
        Nlist = sample(Nlist, samp_size)
        Slist = sample(Slist, samp_size)
        Prodlist = sample(Prodlist, samp_size)
        MAXUlist = sample(MAXUlist, samp_size)
        Rlist = sample(Rlist, samp_size)
        Qlist = sample(Qlist, samp_size)
        MCT = sample(MCT, samp_size)

        if basic == True:
            return [np.mean(Glist), np.mean(Nlist), np.mean(Slist), np.mean(Rlist),
                    np.mean(Qlist), np.mean(MAXUlist), burnIn,
                    lag, np.mean(Prodlist), np.mean(MCT), Hurst, pval]

        elif basic == False:
            TOlist = sample(TOlist, samp_size)
            SoNlist = sample(SoNlist, samp_size)
            Hlist = sample(Hlist, samp_size)
            Evarlist = sample(Evarlist, samp_size)
            CTlist = sample(CTlist, samp_size)

            return [np.mean(Glist), np.mean(Nlist), np.mean(Rlist),
                    np.mean(TOlist), np.mean(Qlist), np.mean(CTlist),
                    np.mean(Evarlist), np.mean(Hlist), RADlist,
                    np.mean(SoNlist), np.mean(MAXUlist), burnIn,
                    lag, np.mean(Prodlist), np.mean(MCT), Hurst, pval]


    return ['no result']
Exemplo n.º 3
0
def Hbide(V, REStime, Rcons, Pcons, PropQ, time, mean, std, Kq, lgp, maint,
          res_pulse, im_pulse, env_noise, spatial_het, basic, system, disp_mu,
          disp_std):
    """
    V         :  Volume

    Rcons     :  resource concentration

    Pcons     :  propagule concentration

    maint     :  resource loss due to cell maintenance

    REStime   :  residence time

    time      :  number of time steps to run simulation. Needs to be large
    enough to allow the community to reach a relatively stable state

    dormancy  :  designate whether dormancy is allowed. If dormancy is True,
    then cell quotas of 0 result in dormancy, if dormancy = False, then cell
    quotas of 0 result in death and immediate 'removal'

    """

    r = V / REStime  # rate of flow
    TR = Rcons * V  # total resources in the local environment

    num_in = int(round(r * Pcons))
    if num_in < 1 and Pcons > 1:
        return ['Continuously empty system']

    Nlist = []  # total abundance
    Glist = []  # average growth rate
    Slist = []  # richness
    Prodlist = []  # productivity list
    Rlist = []  # total resources
    Qlist = []  # cell quota
    MAXUlist = []
    Tlist = []  # number of generations in the system
    MCT = []

    if basic == False:
        SoNlist = []  # average species abundance
        TOlist = []  # biomass turnover
        Evarlist = []  # evenness
        Hlist = []  # Shannon's diversity
        CTlist = []  # compositional turnover
        RADlist = []  # list of RADs

    maxUptake_list = []
    maxUptake_dict = {}

    xcoords = []
    ycoords = []
    zcoords = []

    DispParamsDict = {}

    Qs1 = []
    Qs2 = list(Qs1)
    N = len(Qs1)

    Slist1 = []
    Slist2 = list(Slist1)

    inds1 = []
    inds2 = list(inds1)

    ID = 0
    lag = 0
    """ Initial bout of immigration """
    init_n = 1000
    Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, xcoords, ycoords, zcoords = bide.immigration(
        system, V, Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict,
        maxUptake_list, DispParamsDict, mean, std, lgp, init_n, PropQ, xcoords,
        ycoords, zcoords, disp_mu, disp_std)

    Nlist2 = []
    pastBurnIn = 'no'

    Hurst = float()
    pval = float()

    for t in range(time):
        """ Resource resupply """
        TR += r * Rcons  # Total Resources increase due to inflow
        """ Immigration """
        if system != 'ideal':
            Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict, maxUptake_list, DispParamsDict, xcoords, ycoords, zcoords = bide.immigration(
                system, V, Qs2, Slist2, inds2, Tlist, ID, maxUptake_dict,
                maxUptake_list, DispParamsDict, mean, std, lgp, num_in, PropQ,
                xcoords, ycoords, zcoords, disp_mu, disp_std)
        """ Growth """
        Qs2, Slist2, inds2, maxUptake_list, Tlist, TR, glist, xcoords, ycoords, zcoords = bide.growth(
            Qs2, Slist2, inds2, maxUptake_list, Tlist, TR, Kq, maint, xcoords,
            ycoords, zcoords)

        N = len(Qs2)
        if N == 0:
            return ['N = 0']
        """ Reproduction """
        Qs2, Slist2, inds2, Tlist, maxUptake_list, Kq, ID, prod, xcoords, ycoords, zcoords = bide.reproduction(
            Qs2, Slist2, inds2, Tlist, maxUptake_list, Kq, ID, maint, xcoords,
            ycoords, zcoords)
        """ Check community variables and list lengths"""
        check = checks(Qs2, Slist2, inds2, Tlist, xcoords, ycoords, zcoords)
        if check[0] != 'pass':
            return check
        """ Emigration """  # will eventually be modified to allow individuals to naturally flow out
        Qs2, Slist2, inds2, Tlist, maxUptake_list, xcoords, ycoords, zcoords = bide.emigration(
            Qs2, Slist2, inds2, Tlist, maxUptake_list, r, V, xcoords, ycoords,
            zcoords, system)

        N = len(Qs2)
        if N == 0:
            return ['N = 0 after emigration']
        """ Dispersal """
        Qs2, Slist2, inds2, Tlist, maxUptake_list, DispParamsDict, Kq, ID, xcoords, ycoords, zcoords = bide.dispersal(
            V, Qs2, Slist2, inds2, Tlist, maxUptake_list, DispParamsDict, Kq,
            ID, xcoords, ycoords, zcoords, system)
        """ Outflow """
        TR, V = bide.outflow(TR, r, V)

        N = len(Qs2)
        if N == 0:
            return ['N = 0']

        if pastBurnIn == 'no':

            Nlist2.append(N)
            if len(Nlist2) > 500:

                Hurst, pval = timeSeries.get_burnin(Nlist2)
                if Hurst < 0.5 and pval < 0.01:
                    pastBurnIn = 'yes'
                    Nlist2 = []
                    burnIn = t
                    time += time  # let the simulation go longer

                else:
                    pastBurnIn = 'no'

        if pastBurnIn == 'yes':
            """ Record community info """

            Glist.append(np.mean(glist))
            Nlist.append(prod)
            Slist.append(len(set(Slist2)))
            Prodlist.append(prod)
            Rlist.append(float(TR))
            Qlist.append(float(sum(Qs2) / len(Qs2)))
            MAXUlist.append(float(np.mean(maxUptake_list)))

            if min(Tlist) == 0 and max(Tlist) == 0:
                MCT.append(0)
            else:
                Tlist_noZeros = filter(lambda a: a != 0, Tlist)
                MCT.append(float(np.mean(Tlist_noZeros)))

            if basic == False:

                S1 = set(Slist1)
                s1 = len(S1)
                S2 = set(Slist2)
                s2 = len(S2)
                c = len(S1 & S2)
                CT = ((s1 - c) + (s2 - c)) / np.mean([s1, s2])
                # Whittaker's tunover (species)

                I1 = set(inds1)
                i1 = len(I1)
                I2 = set(inds2)
                i2 = len(I2)
                c = len(I1 & I2)
                TO = ((i1 - c) + (i2 - c)) / np.mean([i1, i2])
                # Whittaker's tunover (individuals)

                RAD = []  # Generate the rank-abundance distribution (RAD)
                for i in S2:
                    ab = Slist2.count(i)
                    RAD.append(ab)

                RAD.sort()
                RAD.reverse()

                RADtaulist = [10, 100, 1000]
                ct = RADtaulist.count(REStime)
                if ct > 0 and t == time - 1:
                    RADlist = list([V, REStime, RAD])

                TOlist.append(TO)
                SoNlist.append(float(N / s2))

                Hlist.append(float(metrics.Shannons_even(RAD)))
                Evarlist.append(float(metrics.e_var(RAD)))
                CTlist.append(float(CT))

            if len(Nlist) >= 500:

                #lag = timeSeries.get_uncorrelated(Nlist)
                if REStime <= 10:
                    lag = 10
                else:
                    lag = REStime

                if lag > 0:
                    samp_size = int(round(len(Nlist) / lag))

                    if samp_size >= 10:

                        Glist = sample(Glist, samp_size)
                        Nlist = sample(Nlist, samp_size)
                        Slist = sample(Slist, samp_size)
                        Prodlist = sample(Prodlist, samp_size)
                        MAXUlist = sample(MAXUlist, samp_size)
                        Rlist = sample(Rlist, samp_size)
                        Qlist = sample(Qlist, samp_size)
                        MCT = sample(MCT, samp_size)

                        if basic == True:
                            return [
                                np.mean(Glist),
                                np.mean(Nlist),
                                np.mean(Slist),
                                np.mean(Rlist),
                                np.mean(Qlist),
                                np.mean(MAXUlist), burnIn, lag,
                                np.mean(Prodlist),
                                np.mean(MCT), Hurst, pval
                            ]

                        elif basic == False:
                            TOlist = sample(TOlist, samp_size)
                            SoNlist = sample(SoNlist, samp_size)
                            Hlist = sample(Hlist, samp_size)
                            Evarlist = sample(Evarlist, samp_size)
                            CTlist = sample(CTlist, samp_size)

                            return [
                                np.mean(Glist),
                                np.mean(Nlist),
                                np.mean(Rlist),
                                np.mean(TOlist),
                                np.mean(Qlist),
                                np.mean(CTlist),
                                np.mean(Evarlist),
                                np.mean(Hlist), RADlist,
                                np.mean(SoNlist),
                                np.mean(MAXUlist), burnIn, lag,
                                np.mean(Prodlist),
                                np.mean(MCT), Hurst, pval
                            ]
        """ saving this generations lists """
        Slist1 = list(Slist2)
        inds1 = list(inds2)
        Qs1 = list(Qs2)

        if t == time - 1 and pastBurnIn == 'no':
            return [
                'failed to reach stationarity in ' + str(time) +
                ' generations, H = ' + str(round(Hurst, 3)) + ', p = ' +
                str(round(pval, 3))
            ]

    #lag = timeSeries.get_uncorrelated(Nlist)
    if REStime <= 10:
        lag = 10
    else:
        lag = REStime

    if lag == 0:
        return [
            'no sufficient time lag in ' + str(len(Nlist)) + ' generations'
        ]

    else:
        samp_size = int(round(len(Nlist) / lag))
        if samp_size < 10:
            return [
                'insufficient sample of unbiased time points from ' +
                str(len(Nlist)) + ' generations'
            ]

        Glist = sample(Glist, samp_size)
        Nlist = sample(Nlist, samp_size)
        Slist = sample(Slist, samp_size)
        Prodlist = sample(Prodlist, samp_size)
        MAXUlist = sample(MAXUlist, samp_size)
        Rlist = sample(Rlist, samp_size)
        Qlist = sample(Qlist, samp_size)
        MCT = sample(MCT, samp_size)

        if basic == True:
            return [
                np.mean(Glist),
                np.mean(Nlist),
                np.mean(Slist),
                np.mean(Rlist),
                np.mean(Qlist),
                np.mean(MAXUlist), burnIn, lag,
                np.mean(Prodlist),
                np.mean(MCT), Hurst, pval
            ]

        elif basic == False:
            TOlist = sample(TOlist, samp_size)
            SoNlist = sample(SoNlist, samp_size)
            Hlist = sample(Hlist, samp_size)
            Evarlist = sample(Evarlist, samp_size)
            CTlist = sample(CTlist, samp_size)

            return [
                np.mean(Glist),
                np.mean(Nlist),
                np.mean(Rlist),
                np.mean(TOlist),
                np.mean(Qlist),
                np.mean(CTlist),
                np.mean(Evarlist),
                np.mean(Hlist), RADlist,
                np.mean(SoNlist),
                np.mean(MAXUlist), burnIn, lag,
                np.mean(Prodlist),
                np.mean(MCT), Hurst, pval
            ]

    return ['no result']
Exemplo n.º 4
0
    ct += 1
    RowID += 1

    shuffle(x)
    t2 = float()
    t1 = time.clock()
    for xi in x:

        # Inflow of resources
        if xi == 0: ResLists, ResDict, res_in = bide.ResIn(ResLists, ResDict, params, ct, ComplexityLevels)

        # Immigration
        elif xi == 1: IndDict, SpDicts = bide.immigration(IndDict, SpDicts, params, ct, ComplexityLevels)

        # Individual Dispersal
        elif xi == 2 and '-none-' not in SC: IndDict, ResList, ResDict, numDead = bide.dispersal(IndDict, SpDicts, ResLists, ResDict, params, ComplexityLevels, numDead)

        # Resource Dispersal
        elif xi == 3: ResLists = bide.res_dispersal(ResLists, params, ct, ComplexityLevels)

        # Consumption
        elif xi == 4: ResLists, ResDict, IndDict, encounters, numDead = bide.consume(IndDict, SpDicts, ResLists, ResDict, params, ComplexityLevels, numDead)

        # Reproduction
        elif xi == 5: PRODI, IndDicts, ResLists, ResDict, numDead = bide.reproduce(IndDict, SpDicts, ResLists, ResDict, params, ComplexityLevels, numDead)

        # Maintenance
        elif xi == 6: IndDict, ResLists, ResDict, numDead = bide.maintenance(IndDict, SpDicts, ResLists, ResDict, ComplexityLevels, numDead)

        # Transition to or from dormancy
        elif xi == 7: IndDict, ResLists, ResDict, numDead = bide.transition(IndDict, SpDicts, ResLists, ResDict, ComplexityLevels, numDead)