Exemple #1
0
def iter_procs(iD, sD, rD, ps, ct, minlim):
    pr, D = 0, 0
    pD = float('NaN')
    h, r, u, nr, im, Si = ps
    procs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    shuffle(procs)
    for p in procs:
        if p is 0: rD = bd.ResIn(rD, ps)
        elif p is 1: rD = bd.res_flow(rD, ps)
        elif p is 2: sD, iD = bd.immigration(sD, iD, ps)
        elif p is 3: iD = bd.ind_flow(iD, ps)
        elif p is 4: iD = bd.ind_disp(iD, ps)
        elif p is 5: iD, rD, D = bd.consume(iD, rD, ps)
        elif p is 6: iD = bd.grow(iD, ps)
        elif p is 7: iD = bd.transition(iD, ps)
        elif p is 8: iD = bd.maintenance(iD, ps)
        elif p is 9: sD, iD, pr = bd.reproduce(sD, iD, ps)

    avgQ = []
    Sz = []
    Ris = []
    SpIDs = []
    states = []
    if len(list(iD)) > 0:
        for k, v in iD.items():
            Ris.append(v['q'] / (v['mt'] * v['sz']))
            avgQ.append(v['q'])
            Sz.append(v['sz'])
            SpIDs.append(v['sp'])
            states.append(v['st'])
        avgQ = mean(avgQ)
        Sz = mean(Sz)
        N = len(states)
        pD = states.count('d') / N
        S = len(list(set(SpIDs)))
        Ri = mean(Ris)

        return [
            iD, sD, rD, N, S,
            len(list(rD)), ct + 1, pr, pD, avgQ, Sz, D, Ri
        ]

    else:
        return [
            iD, sD, rD, 0, 0,
            len(list(rD)), ct + 1, 0,
            float('NaN'),
            float('NaN'),
            float('NaN'),
            float('NaN'),
            float('NaN')
        ]
Exemple #2
0
def iter_procs(iD, sD, rD, ps, ct, minlim):
    pr, D = 0, 0
    pD = float('NaN')
    h, r, u, nr, im, Si = ps
    procs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    shuffle(procs)
    for p in procs:
        if p is 0: rD = bd.ResIn(rD, ps)
        elif p is 1: rD = bd.res_flow(rD, ps)
        elif p is 2: sD, iD = bd.immigration(sD, iD, ps)
        elif p is 3: iD = bd.ind_flow(iD, ps)
        elif p is 4: iD = bd.ind_disp(iD, ps)
        elif p is 5: iD, rD, D = bd.consume(iD, rD, ps)
        elif p is 6: iD = bd.grow(iD, ps)
        elif p is 7: iD = bd.transition(iD, ps)
        elif p is 8: iD = bd.maintenance(iD, ps)
        elif p is 9: sD, iD, pr = bd.reproduce(sD, iD, ps)

    avgQ = []
    Sz = []
    Ris = []
    SpIDs = []
    states = []
    if len(list(iD)) > 0:
        for k, v in iD.items():
            Ris.append(v['q']/(v['mt']*v['sz']))
            avgQ.append(v['q'])
            Sz.append(v['sz'])
            SpIDs.append(v['sp'])
            states.append(v['st'])
        avgQ = mean(avgQ)
        Sz = mean(Sz)
        N = len(states)
        pD = states.count('d')/N
        S = len(list(set(SpIDs)))
        Ri = mean(Ris)

        return [iD, sD, rD, N, S, len(list(rD)), ct+1, pr, pD, avgQ, Sz, D, Ri]

    else: return [iD, sD, rD, 0, 0, len(list(rD)), ct+1, 0, float('NaN'),
            float('NaN'), float('NaN'), float('NaN'), float('NaN')]
Exemple #3
0
def nextFrame(arg):
    """ Function called for each successive animation frame; arg is the frame number """

    global ADs, ADList, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth, fixed, p, BurnIn, t, num_sims, width, height, Rates, u0, rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, SpColorDict, GrowthDict, N_RD, P_RD, C_RD, DispDict, MaintDict, one9th, four9ths, one36th, barrier, gmax, dmax, maintmax, IndIDs, Qs, IndID, IndTimeIn, IndExitAge, IndX, IndY, Ind_scatImage, SpeciesIDs, EnvD, TY, tracer_scatImage, TTimeIn, TIDs, TExitAge, TX, RTypes, RX, RY, RID, RIDs, RVals, RTimeIn, RExitAge, resource_scatImage, bN, bS, bE, bW, bNE, bNW, bSE, bSW, ct1, Mu, Maint, motion, reproduction, speciation, seedCom, m, r, nNi, nP, nC, rmax, sim, RAD, splist, N, ct, splist2, WTs, Jcs, Sos, RDens, RDiv, RRich, S, ES, Ev, BP, SD, Nm, sk, T, R, LowerLimit, prod_i, prod_q, viscosity, alpha, Ts, Rs, PRODIs, Ns, TTAUs, INDTAUs, RDENs, RDIVs, RRICHs, Ss, ESs, EVs, BPs, SDs, NMAXs, SKs, MUs, MAINTs, PRODNs, PRODPs, PRODCs, lefts, bottoms, Gs, Ms, NRs, PRs, CRs, Ds, RTAUs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, amp, freq, flux, pulse, phase, disturb, envgrads, barriers

    ct += 1
    #plot_system = 'yes'
    plot_system = 'no'

    # fluctuate flow according to amplitude, frequency, & phase
    u1 = u0 + u0 * (amp * sin(2 * pi * ct * freq + phase))
    if u1 > 1: u1 == 1.0

    # Fluid dynamics
    nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier = LBM.stream(
        [nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier])
    rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW = LBM.collide(
        viscosity, rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, u0)

    # Inflow of tracers
    if motion == 'white_noise' or motion == 'brown_noise':
        numt = 10
        TIDs, TTimeIn, TX, TY = bide.NewTracers(numt, motion, TIDs, TX, TY,
                                                TTimeIn, width, height, 2)

    elif ct == 1:
        numt = 10
        TIDs, TTimeIn, TX, TY = bide.NewTracers(numt, motion, TIDs, TX, TY,
                                                TTimeIn, width, height, 2)

    else:
        numt = 1
        TIDs, TTimeIn, TX, TY = bide.NewTracers(numt, motion, TIDs, TX, TY,
                                                TTimeIn, width, height, u0)

    # moving tracer particles
    if len(TIDs) > 0:
        if motion == 'fluid':
            TIDs, TX, TY, TExitAge, TTimeIn = bide.fluid_movement(
                'tracer', TIDs, TTimeIn, TExitAge, TX, TY, ux, uy, width,
                height, u0)
        else:
            TIDs, TX, TY, TExitAge, TTimeIn = bide.nonfluid_movement(
                'tracer', motion, TIDs, TTimeIn, TExitAge, TX, TY, ux, uy,
                width, height, u0)

    # Inflow of resources
    if motion == 'white_noise' or motion == 'brown_noise':
        u1 = 2
    RTypes, RVals, RX, RY, RIDs, RID, RTimeIn = bide.ResIn(
        motion, RTypes, RVals, RX, RY, RID, RIDs, RTimeIn, r, rmax, nNi, nP,
        nC, width, height, u1)

    # resource flow
    Lists = [RTypes, RIDs, RID, RVals]
    if len(RTypes) > 0:
        if motion == 'fluid':
            RTypes, RX, RY, RExitAge, RIDs, RID, RTimeIn, RVals = bide.fluid_movement(
                'resource', Lists, RTimeIn, RExitAge, RX, RY, ux, uy, width,
                height, u0)
        else:
            RTypes, RX, RY, RExitAge, RIDs, RID, RTimeIn, RVals = bide.nonfluid_movement(
                'resource', motion, Lists, RTimeIn, RExitAge, RX, RY, ux, uy,
                width, height, u0)

    # Inflow of individuals (immigration)
    if ct == 1:
        SpeciesIDs, IndX, IndY, MaintDict, EnvD, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.immigration(
            dmax, gmax, maintmax, motion, seedCom, 1, SpeciesIDs, IndX, IndY,
            width, height, MaintDict, EnvD, envgrads, GrowthDict, DispDict,
            SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, nNi,
            nP, nC, u1, alpha, GrowthList, MaintList, N_RList, P_RList,
            C_RList, DispList, ADList)
    else:
        SpeciesIDs, IndX, IndY, MaintDict, EnvD, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.immigration(
            dmax, gmax, maintmax, motion, 1, m, SpeciesIDs, IndX, IndY, width,
            height, MaintDict, EnvD, envgrads, GrowthDict, DispDict,
            SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, nNi,
            nP, nC, u1, alpha, GrowthList, MaintList, N_RList, P_RList,
            C_RList, DispList, ADList)

    # dispersal
    Lists = [
        SpeciesIDs, IndIDs, IndID, Qs, DispDict, GrowthList, MaintList,
        N_RList, P_RList, C_RList, DispList, ADList, Qs
    ]
    if len(SpeciesIDs) > 0:
        if motion == 'fluid':
            SpeciesIDs, IndX, IndY, IndExitAge, IndIDs, IndID, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList, Qs = bide.fluid_movement(
                'individual', Lists, IndTimeIn, IndExitAge, IndX, IndY, ux, uy,
                width, height, u0)
        else:
            SpeciesIDs, IndX, IndY, IndExitAge, IndIDs, IndID, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList, Qs = bide.nonfluid_movement(
                'individual', motion, Lists, IndTimeIn, IndExitAge, IndX, IndY,
                ux, uy, width, height, u0)

    # Chemotaxis
    #SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.chemotaxis(reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, DispDict, SpColorDict, N_RD, P_RD, C_RD, MaintDict, EnvD, envgrads, nNi, nP, nC, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # Forage
    #SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.density_forage(RVals, RX, RY, reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, DispDict, SpColorDict, N_RD, P_RD, C_RD, MaintDict, EnvD, envgrads, nNi, nP, nC, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    PRODI, PRODN, PRODC, PRODP = 0, 0, 0, 0

    p1, TNQ1, TPQ1, TCQ1 = metrics.getprod(Qs)

    # Consume
    RTypes, RVals, RIDs, RID, RTimeIn, RExitAge, RX, RY, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.consume(
        RTypes, RVals, RIDs, RID, RX, RY, RTimeIn, RExitAge, SpeciesIDs, Qs,
        IndIDs, IndID, IndTimeIn, IndX, IndY, width, height, GrowthDict, N_RD,
        P_RD, C_RD, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList,
        DispList, ADList)

    # Reproduction
    SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.reproduce(
        reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn,
        IndX, IndY, width, height, GrowthDict, DispDict, SpColorDict, N_RD,
        P_RD, C_RD, MaintDict, EnvD, envgrads, nNi, nP, nC, GrowthList,
        MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # maintenance
    SpeciesIDs, X, Y, IndExitAge, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.maintenance(
        SpeciesIDs, IndX, IndY, IndExitAge, SpColorDict, MaintDict, EnvD,
        IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList,
        C_RList, DispList, ADList)

    # transition to or from dormancy
    Sp_IDs, IDs, Qs, GrowthList, MaintList, ADList = bide.transition(
        SpeciesIDs, IndIDs, Qs, GrowthList, MaintList, ADList)

    p2, TNQ2, TPQ2, TCQ2 = metrics.getprod(Qs)

    PRODI = p2 - p1
    PRODN = TNQ2 - TNQ1
    PRODP = TPQ2 - TPQ1
    PRODC = TCQ2 - TCQ1

    # disturbance
    if np.random.binomial(1, disturb * u0) == 1:
        SpeciesIDs, X, Y, IndExitAge, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.decimate(
            SpeciesIDs, IndX, IndY, IndExitAge, SpColorDict, MaintDict, EnvD,
            IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList,
            C_RList, DispList, ADList)

    ax = fig.add_subplot(111)
    plt.tick_params(axis='both',
                    which='both',
                    bottom='off',
                    top='off',
                    left='off',
                    right='off',
                    labelbottom='off',
                    labelleft='off')

    if len(SpeciesIDs) >= 1: RAD, splist = bide.GetRAD(SpeciesIDs)
    else: RAD, splist, N, S = [], [], 0, 0

    N, S, tt, rr = sum(RAD), len(RAD), len(TIDs), len(RIDs)
    numD = ADList.count('d')

    if N != len(ADList):
        print N, len(SpeciesIDs), len(ADList)
        print "N != len(ADList)"
        sys.exit()

    if N > 0:
        Title = [
            'Individuals consume resources, grow, reproduce, and die as they move through the environment. \nAverage speed on the x-axis is '
            + str(u0) + ' units per time step. ' + str(len(TExitAge)) +
            ' tracers have passed through.\nN: ' + str(N) + ', S: ' + str(S) +
            ', tracers: ' + str(tt) + ', resources: ' + str(rr) + ', ct: ' +
            str(ct) + ', %dormant: ' + str(round((numD / N) * 100, 2))
        ]
    else:
        Title = [
            'Individuals consume resources, grow, reproduce, and die as they move through the environment. \nAverage speed on the x-axis is '
            + str(u0) + ' units per time step. ' + str(len(TExitAge)) +
            ' tracers have passed through.\nN: ' + str(N) + ', S: ' + str(S) +
            ', tracers: ' + str(tt) + ', resources: ' + str(rr) + ', ct: ' +
            str(ct) + ', %dormant: nan'
        ]

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

    if plot_system == 'yes':
        ##### PLOTTING THE SYSTEM ##############################################
        resource_scatImage.remove()
        tracer_scatImage.remove()
        Ind_scatImage.remove()
        colorlist = []
        sizelist = []
        for i, val in enumerate(SpeciesIDs):
            if ADList[i] == 'a':
                colorlist.append('red')
            elif ADList[i] == 'd':
                colorlist.append('0.3')

            sizelist.append(min(Qs[i]) * 1000)

        resource_scatImage = ax.scatter(RX,
                                        RY,
                                        s=RVals * 100,
                                        c='w',
                                        edgecolor='SpringGreen',
                                        lw=0.6,
                                        alpha=0.3)

        Ind_scatImage = ax.scatter(IndX,
                                   IndY,
                                   s=sizelist,
                                   c=colorlist,
                                   edgecolor='0.2',
                                   lw=0.2,
                                   alpha=0.9)
        tracer_scatImage = ax.scatter(TX,
                                      TY,
                                      s=200,
                                      c='r',
                                      marker='*',
                                      lw=0.0,
                                      alpha=0.6)

    Ns.append(N)

    if N == 0 and BurnIn == 'not done':
        Ns = [Ns[-1]]  # only keep the most recent N value
        BurnIn = 'done'

    if ct > 200 and BurnIn == 'not done':
        if len(Ns) > 100:
            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 > 300 and BurnIn == 'not done':
        Ns = [Ns[-1]]  # only keep the most recent N value
        BurnIn = 'done'

    if BurnIn == 'done':

        PRODIs.append(PRODI)
        PRODNs.append(PRODN)
        PRODPs.append(PRODP)
        PRODCs.append(PRODC)

        if len(RExitAge) > 0:
            RTAUs.append(mean(RExitAge))
        if len(IndExitAge) > 0:
            INDTAUs.append(mean(IndExitAge))
        if len(TExitAge) > 0:
            TTAUs.append(mean(TExitAge))

        # Examining the resource RAD
        if len(RTypes) > 0:
            RRAD, Rlist = bide.GetRAD(RTypes)
            RDens = len(RTypes) / (height * width)
            RDiv = float(metrics.Shannons_H(RRAD))
            RRich = len(Rlist)

        RDENs.append(RDens)
        RDIVs.append(RDiv)
        RRICHs.append(RRich)
        # Number of tracers, resource particles, and individuals
        T, R, N = len(TIDs), len(RIDs), len(SpeciesIDs)

        Ts.append(T)
        Rs.append(R)
        Ss.append(S)

        if N >= 1:

            if R >= 1:
                q = min([10, R])
                #avg_dist = spatial.avg_dist(X, RX, Y, RY, q)
                avg_dist = spatial.nearest_neighbor(X, RX, Y, RY, q)
                AVG_DIST.append(avg_dist)

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

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

            RAD, splist = bide.GetRAD(SpeciesIDs)
            RAD, splist = zip(*sorted(zip(RAD, splist), reverse=True))
            RAD = list(RAD)

            S = len(RAD)
            Ss.append(S)
            # Evenness, Dominance, and Rarity measures
            Ev = metrics.e_var(RAD)
            EVs.append(Ev)
            ES = metrics.e_simpson(RAD)
            ESs.append(ES)

            if len(Ns) == 1:
                splist2 = list(splist)

            if len(Ns) > 1:
                wt = metrics.WhittakersTurnover(splist, splist2)
                jc = metrics.jaccard(splist, splist2)
                so = metrics.sorensen(splist, splist2)
                splist2 = list(splist)
                WTs.append(wt)
                Jcs.append(jc)
                Sos.append(so)

            Nm, BP = [max(RAD), Nm / N]
            NMAXs.append(Nm)
            BPs.append(BP)

            SD = metrics.simpsons_dom(RAD)
            SDs.append(SD)
            sk = stats.skew(RAD)
            SKs.append(sk)

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

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

            Nmeans = [sum(x) / len(x) for x in zip(*N_RList)]
            NRs.append(mean(Nmeans))

            Pmeans = [sum(x) / len(x) for x in zip(*P_RList)]
            PRs.append(mean(Pmeans))

            Cmeans = [sum(x) / len(x) for x in zip(*C_RList)]
            CRs.append(mean(Cmeans))

        #process = psutil.Process(os.getpid())
        #mem = round(process.get_memory_info()[0] / float(2 ** 20), 1)
        # return the memory usage in MB

        if len(Ns) > 100:
            t = time.clock() - t

            #print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(mean(Ss))), 'WT:', round(mean(WTs),2), ':  flow:', u0, 'time:', round(t,1), 'seconds', ':  Ttaus:',round(mean(TTimeIn)), round(mean(TExitAge)), ':  Etau:', round(width/u0)  #' MB:',int(round(mem)), 'p-val =', round(p,3)
            #print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(mean(Ss))), ':  flow:', u0, 'time:', round(t,1), 'seconds', ' height:', str(height), '  Avg dist:', round(mean(AVG_DIST),3), ' f(dormant):',round(mean(ADs),3)
            print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(
                mean(Ss))), '  flow:', u0, 'time:', round(
                    t,
                    1), 'Ttaus:', round(mean(TExitAge), 2), ':  Etau:', round(
                        (width - 1) / u0, 2), 'dormant:', round(mean(ADs), 3)

            t = time.clock()

            SString = str(splist).strip('()')
            RADString = str(RAD).strip('()')
            RADString = str(RAD).strip('[]')
            IndRTD = str(IndExitAge).strip('[]')
            TRTD = str(TExitAge).strip('[]')
            RRTD = str(RExitAge).strip('[]')

            OUT1 = open(GenPath + 'examples/SimData.csv', 'a')
            OUT2 = open(GenPath + 'examples/RADs.csv', 'a')
            OUT3 = open(GenPath + 'examples/Species.csv', 'a')
            OUT4 = open(GenPath + 'examples/IndRTD.csv', 'a')
            OUT5 = open(GenPath + 'examples/TracerRTD.csv', 'a')
            OUT6 = open(GenPath + 'examples/ResRTD.csv', 'a')

            #TTAUs = np.mean(TExitAge), np.mean(TTimeIn)

            outlist = [
                sim, motion,
                mean(PRODIs),
                mean(PRODNs),
                mean(PRODPs),
                mean(PRODCs), r, nNi, nP, nC, rmax, gmax, maintmax, dmax,
                barriers, alpha, seedCom, u0, width - 0.2, height, viscosity,
                N, m,
                mean(RTAUs),
                mean(TExitAge),
                mean(INDTAUs),
                mean(RDENs),
                mean(RDIVs),
                mean(RRICHs),
                mean(Ss),
                mean(ESs),
                mean(EVs),
                mean(BPs),
                mean(SDs),
                mean(NMAXs),
                mean(SKs), T, R, speciation,
                mean(WTs),
                mean(Jcs),
                mean(Sos),
                mean(Gs),
                mean(Ms),
                mean(NRs),
                mean(PRs),
                mean(CRs),
                mean(Ds), amp, flux, freq, phase, disturb,
                mean(SpecGrowth),
                mean(SpecDisp),
                mean(SpecMaint),
                mean(AVG_DIST),
                mean(ADs)
            ]
            outlist = str(outlist).strip('[]')

            print >> OUT1, outlist
            print >> OUT2, RADString
            print >> OUT3, SString
            print >> OUT4, ct1, ',', sim, ',', IndRTD
            print >> OUT5, ct1, ',', sim, ',', TRTD
            print >> OUT6, ct1, ',', sim, ',', RRTD

            OUT1.close()
            OUT2.close()
            OUT3.close()
            OUT4.close()
            OUT5.close()
            OUT6.close()

            ct1 += 1
            ct = 0

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

            n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, rho, ux, uy, bN, bS, bE, bW, bNE, bNW, bSE, bSW = LBM.SetLattice(
                u0, viscosity, width, height, lefts, bottoms, barriers)
            u1 = u0 + u0 * (amp * sin(2 * pi * ct * freq + phase))

            RDens, RDiv, RRich, S, ES, Ev, BP, SD, Nm, sk, Mu, Maint, ct, IndID, RID, N, ct1, T, R, PRODI, PRODQ = [
                0
            ] * 21
            ADList, ADs, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth, SpColorList, GrowthList, MaintList, N_RList, P_RList, C_RList, RColorList, DispList = [
                list([]) for _ in xrange(14)
            ]
            RAD, splist, IndTimeIn, SpeciesIDs, IndX, IndY, IndIDs, Qs, IndExitAge, TX, TY, TExitAge, TIDs, TTimeIn, RX, RY, RIDs, RTypes, RExitAge, RTimeIn, RVals, Gs, Ms, NRs, PRs, CRs, Ds, Ts, Rs, PRODIs, PRODNs, PRODPs, PRODCs, Ns, RTAUs, TTAUs, INDTAUs, RDENs, RDIVs, RRICHs, Ss, ESs, EVs, BPs, SDs, NMAXs, SKs, MUs, MAINTs, WTs, Jcs, Sos, splist2 = [
                list([]) for _ in xrange(53)
            ]

            p = 0
            BurnIn = 'not done'

            #if u0 in Rates:
            if u0 == max(Rates):

                print '\n'
                sim += 1
                if sim > num_sims:
                    print "simplex finished"
                    sys.exit()

                width, height, alpha, motion, reproduction, speciation, seedCom, m, r, nNi, nP, nC, rmax, gmax, maintmax, dmax, amp, freq, flux, pulse, phase, disturb, envgrads, barriers, Rates = rp.get_rand_params(
                    fixed)

                for i in range(barriers):
                    lefts.append(np.random.uniform(0.2, .8))
                    bottoms.append(np.random.uniform(0.1, 0.7))

                n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, rho, ux, uy, bN, bS, bE, bW, bNE, bNW, bSE, bSW = LBM.SetLattice(
                    u0, viscosity, width, height, lefts, bottoms, barriers)
                u1 = u0 + u0 * (amp * sin(2 * pi * ct * freq + phase))


                SpColorDict, GrowthDict, MaintDict, EnvD, N_RD, P_RD, C_RD, RColorDict, DispDict, EnvD = {}, {}, {}, {}, {}, {}, {}, {}, {}, {}

            ####################### REPLACE ENVIRONMENT ########################
            ax = fig.add_subplot(111)
Exemple #4
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, u0, rho, ux, uy
    global n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, SpColorDict, GrowthDict, N_RD
    global P_RD, C_RD, DispDict, MaintDict, one9th, four9ths, one36th, barrier
    global gmax, dmax, maintmax, IndIDs, Qs, IndID, IndTimeIn, IndExitAge, IndX
    global IndY,  Ind_scatImage, SpeciesIDs, EnvD, TY, tracer_scatImage, TTimeIn
    global TIDs, TExitAge, TX, RTypes, RX, RY, RID, RIDs, RVals, RTimeIn, RExitAge
    global resource_scatImage, bN, bS, bE, bW, bNE, bNW, bSE, bSW, ct1, Mu, Maint
    global motion, reproduction, speciation, seedCom, m, r, nNi, nP, nC, rmax, sim
    global RAD, splist, N, ct, splist2, WTs, Jcs, Sos, RDens, RDiv, RRich, S, ES
    global Ev, BP, SD, Nm, sk, T, R, LowerLimit, prod_i, prod_q, viscosity, alpha
    global Ts, Rs, PRODIs, Ns, TTAUs, INDTAUs, RDENs, RDIVs, RRICHs, Ss, ESs, EVs
    global BPs, SDs, NMAXs, SKs, MUs, MAINTs, PRODNs, PRODPs, PRODCs, lefts, bottoms
    global Gs, Ms, NRs, PRs, CRs, Ds, RTAUs, GrowthList, MaintList, N_RList, P_RList
    global C_RList, DispList, amp, freq, flux, pulse, phase, disturb, envgrads
    global barriers, MainFactorDict, RPFDict

    ct += 1
    #plot_system = 'yes'
    plot_system = 'no'

    # fluctuate flow according to amplitude, frequency, & phase
    u1 = u0 + u0*(amp * sin(2*pi * ct * freq + phase))
    if u1 > 1: u1 == 1.0

    # Fluid dynamics
    nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier = LBM.stream([nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier])
    rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW = LBM.collide(viscosity, rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, u0)

    # Inflow of resources
    if motion == 'white_noise' or motion == 'brown_noise':
        u1 = 2
    RTypes, RVals, RX, RY,  RIDs, RID, RTimeIn = bide.ResIn(motion, RTypes, RVals, RX, RY,  RID, RIDs, RTimeIn, r, rmax, nNi, nP, nC, width, height, u1)

    # resource flow
    Lists = [RTypes, RIDs, RID, RVals]
    if len(RTypes) > 0:
        if motion == 'fluid': RTypes, RX, RY,  RExitAge, RIDs, RID, RTimeIn, RVals = bide.fluid_movement('resource', Lists, RTimeIn, RExitAge, RX, RY,  ux, uy, width, height, u0)
        else: RTypes, RX, RY,  RExitAge, RIDs, RID, RTimeIn, RVals = bide.nonfluid_movement('resource', motion, Lists, RTimeIn, RExitAge, RX, RY,  ux, uy, width, height, u0)


    # Inflow of individuals (immigration)
    if ct == 1:
        SpeciesIDs, IndX, IndY,  MaintDict, MainFactorDict, RPFDict, EnvD, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.immigration(mmax, pmax, dmax, gmax, maintmax, motion, seedCom, 1, SpeciesIDs, IndX, IndY,  width, height, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, nNi, nP, nC, u1, alpha, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)
    else:
        SpeciesIDs, IndX, IndY,  MaintDict, MainFactorDict, RPFDict, EnvD, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.immigration(mmax, pmax, dmax, gmax, maintmax, motion, 1, m, SpeciesIDs, IndX, IndY,  width, height, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, N_RD, P_RD, C_RD, nNi, nP, nC, u1, alpha, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)


    # dispersal
    Lists = [SpeciesIDs, IndIDs, IndID, Qs, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList]
    if len(SpeciesIDs) > 0:
        if motion == 'fluid': SpeciesIDs, IndX, IndY,  IndExitAge, IndIDs, IndID, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList, Qs = bide.fluid_movement('individual', Lists, IndTimeIn, IndExitAge, IndX, IndY,  ux, uy, width, height, u0)
        else: SpeciesIDs, IndX, IndY, IndExitAge, IndIDs, IndID, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.nonfluid_movement('individual', motion, Lists, IndTimeIn, IndExitAge, IndX, IndY,  ux, uy, width, height, u0)

    # Chemotaxis
    #SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.chemotaxis(reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, DispDict, SpColorDict, N_RD, P_RD, C_RD, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, nNi, nP, nC, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # Forage
    #SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.density_forage(RVals, RX, RY, reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, DispDict, SpColorDict, N_RD, P_RD, C_RD, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, nNi, nP, nC, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    PRODI, PRODN, PRODC, PRODP = 0, 0, 0, 0
    p1, TNQ1, TPQ1, TCQ1 = metrics.getprod(Qs)

    # Consume
    #RTypes, RVals, RIDs, RID, RTimeIn, RExitAge, RX, RY,  SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.consume(RTypes, RVals, RIDs, RID, RX, RY,  RTimeIn, RExitAge, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, N_RD, P_RD, C_RD, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # Reproduction
    SpeciesIDs, Qs, IndIDs, ID, TimeIn, X, Y, GrowthDict, DispDict, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.reproduce(reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndX, IndY,  width, height, GrowthDict, DispDict, SpColorDict, N_RD, P_RD, C_RD, MaintDict, MainFactorDict, RPFDict, EnvD, envgrads, nNi, nP, nC, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # maintenance
    #SpeciesIDs, X, Y, IndExitAge, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.maintenance(SpeciesIDs, IndX, IndY,  IndExitAge, SpColorDict, MaintDict, MainFactorDict, RPFDict, EnvD, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    # transition to or from dormancy
    Sp_IDs, IDs, Qs, GrowthList, MaintList, ADList = bide.transition(SpeciesIDs, IndIDs, Qs, GrowthList, MaintList, MainFactorDict, RPFDict,  ADList)


    p2, TNQ2, TPQ2, TCQ2 = metrics.getprod(Qs)

    PRODI = p2 - p1
    PRODN = TNQ2 - TNQ1
    PRODP = TPQ2 - TPQ1
    PRODC = TCQ2 - TCQ1

    # disturbance
    #if np.random.binomial(1, disturb*u0) == 1: SpeciesIDs, X, Y, IndExitAge, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList = bide.decimate(SpeciesIDs, IndX, IndY,  IndExitAge, SpColorDict, MaintDict, MainFactorDict, RPFDict, EnvD, IndIDs, IndTimeIn, Qs, GrowthList, MaintList, N_RList, P_RList, C_RList, DispList, ADList)

    ax = fig.add_subplot(111)
    plt.tick_params(axis='both', which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off')

    if len(SpeciesIDs) >= 1:  RAD, splist = bide.GetRAD(SpeciesIDs)
    else: RAD, splist, N, S = [], [], 0, 0

    N, S, tt, rr = sum(RAD), len(RAD), len(TIDs), len(RIDs)
    numD = ADList.count('d')

    if N != len(ADList):
        print N, len(SpeciesIDs), len(ADList)
        print "N != len(ADList)"
        sys.exit()

    if N > 0:
        Title = ['Individuals consume resources, grow, reproduce, and die as they move through the environment. \nAverage speed on the x-axis is '+str(u0)+' units per time step. '+str(len(TExitAge))+' tracers have passed through.\nN: '+str(N)+', S: '+str(S)+', tracers: '+str(tt)+', resources: '+str(rr)+', ct: '+str(ct)+', %dormant: '+str(round((numD/N)*100, 2))]
    else:
        Title = ['Individuals consume resources, grow, reproduce, and die as they move through the environment. \nAverage speed on the x-axis is '+str(u0)+' units per time step. '+str(len(TExitAge))+' tracers have passed through.\nN: '+str(N)+', S: '+str(S)+', tracers: '+str(tt)+', resources: '+str(rr)+', ct: '+str(ct)+', %dormant: nan']


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

    if plot_system == 'yes':
        ##### PLOTTING THE SYSTEM ##############################################
        resource_scatImage.remove()
        tracer_scatImage.remove()
        Ind_scatImage.remove()
        colorlist = []
        sizelist = []
        for i, val in enumerate(SpeciesIDs):
            if ADList[i] == 'a':
                colorlist.append('red')
            elif ADList[i] == 'd':
                colorlist.append('0.3')

            sizelist.append(min(Qs[i]) * 1000)

        resource_scatImage = ax.scatter(RX, RY, s = RVals*100, c = 'w', edgecolor = 'SpringGreen', lw = 0.6, alpha=0.3)

        Ind_scatImage = ax.scatter(IndX, IndY, s = sizelist, c = colorlist, edgecolor = '0.2', lw = 0.2, alpha=0.9)
        tracer_scatImage = ax.scatter(TX, TY, s = 200, c = 'r', marker='*', lw=0.0, alpha=0.6)

    Ns.append(N)

    if N == 0 and BurnIn == 'not done':
        Ns = [Ns[-1]] # only keep the most recent N value
        BurnIn = 'done'

    if ct > 200 and BurnIn == 'not done':
        if len(Ns) > 100:
            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 > 300 and BurnIn == 'not done':
        Ns = [Ns[-1]] # only keep the most recent N value
        BurnIn = 'done'

    if BurnIn == 'done':

        PRODIs.append(PRODI)
        PRODNs.append(PRODN)
        PRODPs.append(PRODP)
        PRODCs.append(PRODC)

        if len(RExitAge) > 0:
            RTAUs.append(mean(RExitAge))
        if len(IndExitAge) > 0:
            INDTAUs.append(mean(IndExitAge))
        if len(TExitAge) > 0:
            TTAUs.append(mean(TExitAge))

        # Examining the resource RAD
        if len(RTypes) > 0:
            RRAD, Rlist = bide.GetRAD(RTypes)
            RDens = len(RTypes)/(height*width)
            RDiv = float(metrics.Shannons_H(RRAD))
            RRich = len(Rlist)

        RDENs.append(RDens)
        RDIVs.append(RDiv)
        RRICHs.append(RRich)
        # Number of tracers, resource particles, and individuals
        T, R, N = len(TIDs), len(RIDs), len(SpeciesIDs)

        Ts.append(T)
        Rs.append(R)
        Ss.append(S)


        if N >= 1:

            if R >= 1:
                q = min([10, R])
                avg_dist = spatial.avg_dist(IndX, RX, IndY, RY, q)
                avg_dist = spatial.nearest_neighbor(IndX, RX, IndY, RY, q)
                AVG_DIST.append(avg_dist)

            spD = DispDict.values()
            spM = MaintDict.values()
            spMF = MainFactorDict.values()
            spRPF = RPFDict.values()
            spG = GrowthDict.values()

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

            RAD, splist = bide.GetRAD(SpeciesIDs)
            RAD, splist = zip(*sorted(zip(RAD, splist), reverse=True))
            RAD = list(RAD)

            S = len(RAD)
            Ss.append(S)
            # Evenness, Dominance, and Rarity measures
            Ev = metrics.e_var(RAD)
            EVs.append(Ev)
            ES = metrics.e_simpson(RAD)
            ESs.append(ES)

            if len(Ns) == 1:
                splist2 = list(splist)

            if len(Ns) > 1:
                wt = metrics.WhittakersTurnover(splist, splist2)
                jc = metrics.jaccard(splist, splist2)
                so = metrics.sorensen(splist, splist2)
                splist2 = list(splist)
                WTs.append(wt)
                Jcs.append(jc)
                Sos.append(so)

            Nm, BP = [max(RAD), Nm/N]
            NMAXs.append(Nm)
            BPs.append(BP)

            SD = metrics.simpsons_dom(RAD)
            SDs.append(SD)
            sk = stats.skew(RAD)
            SKs.append(sk)

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

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

            Nmeans = [sum(x)/len(x) for x in zip(*N_RList)]
            NRs.append(mean(Nmeans))

            Pmeans = [sum(x)/len(x) for x in zip(*P_RList)]
            PRs.append(mean(Pmeans))

            Cmeans = [sum(x)/len(x) for x in zip(*C_RList)]
            CRs.append(mean(Cmeans))


        #process = psutil.Process(os.getpid())
        #mem = round(process.get_memory_info()[0] / float(2 ** 20), 1)
        # return the memory usage in MB

        if len(Ns) > 100:
            t = time.clock() - t


            #print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(mean(Ss))), 'WT:', round(mean(WTs),2), ':  flow:', u0, 'time:', round(t,1), 'seconds', ':  Ttaus:',round(mean(TTimeIn)), round(mean(TExitAge)), ':  Etau:', round(width/u0)  #' MB:',int(round(mem)), 'p-val =', round(p,3)
            #print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(mean(Ss))), ':  flow:', u0, 'time:', round(t,1), 'seconds', ' height:', str(height), '  Avg dist:', round(mean(AVG_DIST),3), ' f(dormant):',round(mean(ADs),3)
            print sim, ' N:', int(round(mean(Ns))), 'S:', int(round(mean(Ss))), '  flow:', u0, 'time:', round(t,1), 'Ttaus:', round(mean(TExitAge),2), ':  Etau:', round((width-1)/u0,2),  'dormant:', round(mean(ADs),3)

            t = time.clock()

            SString = str(splist).strip('()')
            RADString = str(RAD).strip('()')
            RADString = str(RAD).strip('[]')
            IndRTD = str(IndExitAge).strip('[]')
            TRTD = str(TExitAge).strip('[]')
            RRTD = str(RExitAge).strip('[]')

            OUT1 = open(GenPath + '/SimData.csv','a')

            #TTAUs = np.mean(TExitAge), np.mean(TTimeIn)

            outlist = [sim,motion,mean(PRODIs),mean(PRODNs),mean(PRODPs),mean(PRODCs),r,nNi,nP,nC,rmax,gmax,maintmax,dmax,barriers,alpha,seedCom,u0,width-0.2,height,viscosity,N,m,mean(RTAUs), mean(TExitAge) ,mean(INDTAUs),mean(RDENs),mean(RDIVs),mean(RRICHs),mean(Ss),mean(ESs),mean(EVs),mean(BPs),mean(SDs),mean(NMAXs),mean(SKs),T,R,speciation,mean(WTs),mean(Jcs),mean(Sos),mean(Gs),mean(Ms),mean(NRs),mean(PRs),mean(CRs),mean(Ds),amp,flux,freq,phase,disturb, mean(SpecGrowth), mean(SpecDisp), mean(SpecMaint), mean(AVG_DIST), mean(ADs)]
            outlist = str(outlist).strip('[]')

            print>>OUT1, outlist
            OUT1.close()

            ct1 += 1
            ct = 0

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

            n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, rho, ux, uy, bN, bS, bE, bW, bNE, bNW, bSE, bSW = LBM.SetLattice(u0, viscosity, width, height, lefts, bottoms, barriers)
            u1 = u0 + u0*(amp * sin(2*pi * ct * freq + phase))

            RDens, RDiv, RRich, S, ES, Ev, BP, SD, Nm, sk, Mu, Maint, ct, IndID, RID, N, ct1, T, R, PRODI, PRODQ = [0]*21
            ADList, ADs, AVG_DIST, SpecDisp, SpecMaint, SpecGrowth, SpColorList, GrowthList, MaintList, N_RList, P_RList, C_RList, RColorList, DispList = [list([]) for _ in xrange(14)]
            RAD, splist, IndTimeIn, SpeciesIDs, IndX, IndY,  IndIDs, Qs, IndExitAge, TX, TY, TExitAge, TIDs, TTimeIn, RX, RY,  RIDs, RTypes, RExitAge, RTimeIn, RVals, Gs, Ms, NRs, PRs, CRs, Ds, Ts, Rs, PRODIs, PRODNs, PRODPs, PRODCs, Ns, RTAUs, TTAUs, INDTAUs, RDENs, RDIVs, RRICHs, Ss, ESs, EVs,BPs, SDs, NMAXs, SKs, MUs, MAINTs, WTs, Jcs, Sos, splist2 = [list([]) for _ in xrange(53)]

            p = 0
            BurnIn = 'not done'

            #if u0 in Rates:
            if u0 == max(Rates):

                print '\n'
                sim += 1
                if sim > num_sims:
                    print "model finished"
                    sys.exit()

                width, height, alpha, motion, reproduction, speciation, seedCom, m, r, nNi, nP, nC, rmax, gmax, maintmax, dmax, amp, freq, flux, pulse, phase, disturb, envgrads, barriers, Rates, pmax, mmax = rp.get_rand_params(fixed)

                for i in range(barriers):
                    lefts.append(np.random.uniform(0.2, .8))
                    bottoms.append(np.random.uniform(0.1, 0.7))

                n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, rho, ux, uy, bN, bS, bE, bW, bNE, bNW, bSE, bSW = LBM.SetLattice(u0, viscosity, width, height, lefts, bottoms, barriers)
                u1 = u0 + u0*(amp * sin(2*pi * ct * freq + phase))


                SpColorDict, GrowthDict, MaintDict, MainFactorDict, RPFDict, EnvD, N_RD, P_RD, C_RD, RColorDict, DispDict, EnvD = {}, {}, {}, {}, {}, {}, {}, {}, {}, {}


            ####################### REPLACE ENVIRONMENT ########################
            ax = fig.add_subplot(111)
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
Exemple #6
0
        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)

        t2 = time.clock() - t1
        if t2 >= 0.12: break

    #if t2 < 0.12: time.sleep(0.12 - t2)
    N = len(IndDict.keys())
    Ns.append(N)
    Rvs = ResLists[0]
    Rvs.sort()
Exemple #7
0
def nextFrame(arg):	# arg is the frame number

    print arg
    plot_system = 'yes'
    logdata = 'no'
    global width, height, length, Rates, u0, shift, sign, rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW
    global SpColorDict, GrowthDict, ResUseDict, DispDict, MaintDict, one9th, four9ths, one36th, barrier
    global IndIDs, Qs, IndID, IndTimeIn, IndExitAge, IndXcoords, IndYcoords, IndZcoords, Ind_scatImage, SpeciesIDs

    global TracerYcoords, tracer_scatImage, TracerTimeIn, TracerZcoords, TracerIDs, TracerExitAge, TracerXcoords
    global ResTypes, ResXcoords, ResYcoords, ResZcoords, ResID, ResIDs, ResVals, ResTimeIn, ResExitAge, resource_scatImage
    global avg_Q, avg_maint, avg_disp, avg_res, avgTau, avg_growth, avg_prey, avg_symb, avg_parasite

    global barrierN, barrierS, barrierE, barrierW, barrierNE, barrierNW, barrierSE, barrierSW
    global BarrierWidth, BarrierHeight, BarrierXcoords1, BarrierYcoords1, BarrierXcoords2, BarrierYcoords2

    global ct1, Mu, Maint, motion, D, reproduction, speciation, predators, parasites, symbionts
    global env_gradient, seedcom, m, r, nr, rmax, sim, RAD, splist, N, TracerTau, IndTau, ct
    global ResDens, ResDiv, ResRich, S, ES, Ev, BP, SD, Nm, sk, T, R, LowerLimit, prod_i, prod_q, viscosity, alpha
    global Ts, Rs, PRODIs, PRODQs, Ns, TRACERTAUs, INDTAUs, RESDENs, RESDIVs, RESRICHs, Ss, ESs, EVs, BPs, SDs, NMAXs, SKs, MUs, MAINTs, RESTAUs

    for step in range(1): # adjust number of steps for smooth animation
        # inflow of tracers
        TracerIDs, TracerTimeIn, TracerXcoords, TracerYcoords, TracerZcoords = bide.NewTracers(motion, TracerIDs, TracerXcoords, TracerYcoords, TracerZcoords, TracerTimeIn, width, height, length, u0, D)

        # inflow of resources
        ResTypes, ResVals, ResXcoords, ResYcoords, ResZcoords, ResIDs, ResID, ResTimeIn = bide.ResIn(motion, ResTypes, ResVals, ResXcoords, ResYcoords, ResZcoords, ResID, ResIDs, ResTimeIn, r, rmax, nr, width, height, length, u0, D)

        # immigration
        if ct == 0:
            ct = 1
            SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, MaintDict, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, ResUseDict = bide.immigration(motion, seedcom, SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, width, height, length, MaintDict, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, ResUseDict, nr, u0, alpha, D)
        else:
            SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, MaintDict, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, ResUseDict = bide.immigration(motion, m, SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, width, height, length, MaintDict, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, ResUseDict, nr, u0, alpha, D)


        if motion == 'fluid' or motion == 'conveyor':  # a 'conveyor' belt action wherein y-coordinates never change occurs when there is 0 turbulence

            # stream & collide
            nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, shift, sign = LBM.stream([nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, shift, sign])
            rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW = LBM.collide(viscosity, rho, ux, uy, n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, u0)

            # dispersal
            Lists = [SpeciesIDs, IndIDs, IndID, Qs, DispDict]
            if len(SpeciesIDs) > 0: SpeciesIDs, IndXcoords, IndYcoords, IndExitAge, IndIDs, IndID, IndTimeIn, Qs = bide.fluid_movement('individual', Lists, IndTimeIn, IndExitAge, IndXcoords, IndYcoords, ux, uy, width, height, u0)

            # resource flow
            Lists = [ResTypes, ResIDs, ResID, ResVals]
            if len(ResTypes) > 0: ResTypes, ResXcoords, ResYcoords, ResExitAge, ResIDs, ResID, ResTimeIn, ResVals = bide.fluid_movement('resource', Lists, ResTimeIn, ResExitAge, ResXcoords, ResYcoords, ux, uy, width, height, u0)

            # moving tracer particles
            if len(TracerIDs) > 0: TracerIDs, TracerXcoords, TracerYcoords, TracerExitAge, TracerTimeIn = bide.fluid_movement('tracer', TracerIDs, TracerTimeIn, TracerExitAge, TracerXcoords, TracerYcoords, ux, uy, width, height, u0)

        elif motion == 'random_walk' or motion == 'unidirectional':

            # Moving tracer particles
            if len(TracerIDs) > 0: TracerIDs, TracerExitAge, TracerTimeIn, TracerXcoords, TracerYcoords, TracerZcoords = bide.nonfluid_movement('tracer', motion, TracerIDs, TracerExitAge, TracerTimeIn, TracerXcoords, TracerYcoords, TracerZcoords, width, height, length, u0, D)

            # Moving resource particles
            if len(ResTypes) > 0:
                Lists = [ResTypes, ResIDs, ResVals]
                Lists, ResExitAge, ResTimeIn, Xcoords, Ycoords, Zcoords = bide.nonfluid_movement('resource', motion, Lists, ResExitAge, ResTimeIn, ResXcoords, ResYcoords, ResZcoords, width, height, length, u0, D)
                ResTypes, ResIDs, ResVals = Lists
            # Moving individuals
            if len(SpeciesIDs) > 0:
                Lists = [SpeciesIDs, IndIDs, Qs, DispDict]
                Lists, IndExitAge, IndTimeIn, Xcoords, Ycoords, Zcoords = bide.nonfluid_movement('individual', motion, Lists, IndExitAge, IndTimeIn, IndXcoords, IndYcoords, IndZcoords, width, height, length, u0, D)
                SpeciesIDs, IndIDs, Qs = Lists

        # consume & reproduce
        p1, q1 = [len(IndIDs), sum(Qs)]
        ResTypes, ResVals, ResIDs, ResID, ResTimeIn, ResExitAge, ResXcoords, ResYcoords, ResZcoords, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndXcoords, IndYcoords, IndZcoords = bide.consume(ResTypes, ResVals, ResIDs, ResID, ResXcoords, ResYcoords, ResZcoords, ResTimeIn, ResExitAge, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndXcoords, IndYcoords, IndZcoords, width, height, length, GrowthDict, ResUseDict, DispDict, D)
        SpeciesIDs, Qs, IDs, ID, TimeIn, Xcoords, Ycoords, Zcoords, GrowthDict, DispDict = bide.reproduce(reproduction, speciation, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndXcoords, IndYcoords, IndZcoords, width, height, length, GrowthDict, DispDict, SpColorDict, ResUseDict, MaintDict, D, nr)
        PRODI, PRODQ = [len(IndIDs) - p1, sum(Qs) - q1]

        # maintenance
        SpeciesIDs, Xcoords, Ycoords, Zcoords, IndExitAge, IndIDs, IndTimeIn, Qs = bide.maintenance(SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, IndExitAge, SpColorDict, MaintDict, IndIDs, IndTimeIn, Qs, D)

        """
        # predation
        p1, n1 = [len(PredIDs), len(IndIDs)]
        PredIDs, PredID, PredTimeIn, PredXcoords, PredYcoords, PredZcoords, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndXcoords, IndYcoords, IndZcoords = bide.predation(predation(PredIDs, PredID, PredXcoords, PredYcoords, PredZcoords, PredTimeIn, IndExitAge, SpeciesIDs, Qs, IndIDs, IndID, IndTimeIn, IndXcoords, IndYcoords, IndZcoords, width, height, length, D)
        pred_i, pred_n = [len(PredIDs) - p1, sum(IndIDs) - n1]
        """

    ########## PLOT THE SYSTEM #################################################
    if D == 3: ax = fig.add_subplot(111, projection='3d')
    else: ax = fig.add_subplot(111)
    plt.tick_params(axis='both', which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off')

    if len(SpeciesIDs) >= 1: RAD, splist = bide.GetRAD(SpeciesIDs)
    else: RAD, splist, N, S = [], [], 0, 0

    N, S, tt, rr = sum(RAD), len(RAD), len(TracerIDs), len(ResIDs)

    Title = ['Individuals consume resources, grow, reproduce, and die as they move through the environment.'
    '\nAverage speed on the x-axis is '+str(u0)+' units per time step. '+str(len(TracerExitAge))+' tracers have passed through.',
           '\nMotion is '+motion+'; N: '+str(N)+', S: '+str(S)+', tracers: '+str(tt)+', resources: '+str(rr)+', replicate: '+str(len(Ns))]

    txt.set_text(' '.join(Title))
    ax.set_ylim(0, height)
    ax.set_xlim(0, width)
    if D == 3: ax.set_zlim(0,length)

    if plot_system == 'yes':

        ##### PLOTTING THE INDIVIDUALS ############################################
        resource_scatImage.remove()
        tracer_scatImage.remove()
        Ind_scatImage.remove()

        colorlist = []
        sizelist = []
        for i, val in enumerate(SpeciesIDs):
            colorlist.append(SpColorDict[val])
            sizelist.append(Qs[i] * 1000)

        if D == 2: resource_scatImage = ax.scatter(ResXcoords, ResYcoords, s = ResVals, c = 'w', edgecolor = 'SpringGreen', lw = 0.6, alpha=0.7)
        elif D == 3: resource_scatImage = ax.scatter(ResXcoords, ResYcoords, ResZcoords, s = ResVals, c = 'w', edgecolor = 'SpringGreen', lw = 0.6, alpha=0.2)

        if D == 2: Ind_scatImage = ax.scatter(IndXcoords, IndYcoords, s = sizelist, c = colorlist, edgecolor = '0.2', lw = 0.2, alpha=0.9)
        elif D == 3: Ind_scatImage = ax.scatter(IndXcoords, IndYcoords, IndZcoords, s = Qs, c = colorlist, edgecolor = '0.2', lw = 0.2, alpha=0.99)

        if D == 2: tracer_scatImage = ax.scatter(TracerXcoords, TracerYcoords, s = 200, c = 'r', marker='*', lw=0.0, alpha=0.6)
        elif D == 3: tracer_scatImage = ax.scatter(TracerXcoords, TracerYcoords, TracerZcoords, s = 200, c = 'r', marker='*', lw=0.0, alpha=0.8)

    plt.draw()

    if u0 == 1.0: LowerLimit = 50
    elif u0 >= 0.5: LowerLimit = 40
    elif u0 >= 0.1: LowerLimit = 20
    elif u0 > 0.01: LowerLimit = 10
    elif u0 == 0.01: LowerLimit = 5

    # Record model values and reset, or not
    if len(TracerExitAge) >= LowerLimit or N == 0:

        PRODIs.append(PRODI)
        PRODQs.append(PRODQ)

        RESTAUs.append(np.mean(ResExitAge))
        INDTAUs.append(np.mean(IndExitAge))
        TRACERTAUs.append(np.mean(TracerExitAge))
        # Examining the resource RAD
        if len(ResTypes) > 0:
            ResRAD, Rlist = bide.GetRAD(ResTypes)
            ResDens = sum(ResTypes)/(height*width)
            ResDiv = float(metrics.Shannons_H(ResRAD))
            ResRich = len(Rlist)

        RESDENs.append(ResDens)
        RESDIVs.append(ResDiv)
        RESRICHs.append(ResRich)

        # Residence times for tracers and Inds
        TracerTau, IndTau, ResTau = [np.mean(TracerExitAge), np.mean(IndExitAge), np.mean(ResExitAge)]
        # Number of tracers, resource particles, and individuals
        T, R, N = len(TracerIDs), len(ResIDs), len(SpeciesIDs)

        if logdata == 'yes':
            IndRTD = str(IndExitAge).strip('[]')
            TracerRTD = str(TracerExitAge).strip('[]')
            ResRTD = str(ResExitAge).strip('[]')
            OUT4 = open(mydir + '/GitHub/hydrobide/results/simulated_data/IndRTD.csv','a')
            OUT5 = open(mydir + '/GitHub/hydrobide/results/simulated_data/TracerRTD.csv','a')
            OUT6 = open(mydir + '/GitHub/hydrobide/results/simulated_data/ResRTD.csv','a')
            print>>OUT4, ct1,',', sim,',', IndRTD
            print>>OUT5, ct1,',', sim,',', TracerRTD
            print>>OUT6, ct1,',', sim,',', ResRTD
            OUT4.close()
            OUT5.close()
            OUT6.close()

        TracerExitAge, IndExitAge, ResExitAge= [],[],[]
        Ts.append(T)
        Rs.append(R)

        if N == 0:
            Ns.append(0)
            Ss.append(0)

        if N >= 1:

            RAD, splist = bide.GetRAD(SpeciesIDs)
            RAD, splist = zip(*sorted(zip(RAD, splist), reverse=True))
            S = len(RAD)
            Ss.append(S)
            Ns.append(N)

            # Specific Growth rate and Maintenance

            mu, maint = [0.0, 0.0]
            for i, sp in enumerate(splist):
                mu += (RAD[i] * GrowthDict[sp])
                maint += (RAD[i] * MaintDict[sp])

            Mu, Maint = [mu/N, maint/N]
            MUs.append(Mu)
            MAINTs.append(Maint)

            # Evenness, Dominance, and Rarity measures
            Ev = metrics.e_var(RAD)
            EVs.append(Ev)

            ES = metrics.e_simpson(RAD)
            ESs.append(ES)

            Nm, BP = [max(RAD), Nm/N]
            NMAXs.append(Nm)
            BPs.append(BP)

            SD = metrics.simpsons_dom(RAD)
            SDs.append(SD)
            sk = stats.skew(RAD)
            SKs.append(sk)


        process = psutil.Process(os.getpid())
        mem = round(process.get_memory_info()[0] / float(2 ** 20), 1)    # return the memory usage in MB

        if len(Ns) >= 1 or N == 0:
            ct = 0
            T, R, PRODI, PRODQ, N, RESTAU, TRACERTAU, INDTAU, RESDENS, RESDIV, RESRICH, S, ES, EV, BP, SD, NMAX, SK, MU, MAINT = [np.mean(Ts), np.mean(Rs), np.mean(PRODIs), np.mean(PRODQs), np.mean(Ns), np.mean(RESTAUs), np.mean(TRACERTAUs), np.mean(INDTAUs), np.mean(RESDENs), np.mean(RESDIVs), np.mean(RESRICHs), np.mean(Ss), np.mean(ESs), np.mean(EVs), np.mean(BPs), np.mean(SDs), np.mean(NMAXs), np.mean(SKs), np.mean(MUs), np.mean(MAINTs)]
            print ct, sim, ' N:', int(round(N)), 'S:', int(round(S)), ' pI:', int(prod_i), 'pQ:', int(prod_q), ': flow:', u0, ' MB:',int(round(mem))

            if logdata == 'yes':
                SString = str(splist).strip('()')
                RADString = str(RAD).strip('()')
                OUT1 = open(mydir + '/GitHub/hydrobide/results/simulated_data/SimData.csv','a')
                OUT2 = open(mydir + '/GitHub/hydrobide/results/simulated_data/RADs.csv','a')
                OUT3 = open(mydir + '/GitHub/hydrobide/results/simulated_data/Species.csv','a')

                print>>OUT1, ct1,',', sim,',', motion,',', D,',', PRODI,',', PRODQ,',', r,',', nr,',', rmax,',', BarrierWidth,',', BarrierHeight,',', alpha,',', seedcom,',', LowerLimit,',', u0,',', width,',', height,',', viscosity,',', N,',', m,',',RESTAU,',',TRACERTAU,',', INDTAU,',', RESDENS,',', RESDIV,',', RESRICH,',', S,',', ES,',', EV,',', BP,',', SD,',', NMAX,',', SK,',', MU,',', MAINT,',',T,',',R
                print>>OUT2, RADString
                print>>OUT3, SString

                OUT1.close()
                OUT2.close()
                OUT3.close()

            ct1 += 1

            if u0 == min(Rates):
                SpColorDict, GrowthDict, MaintDict, ResUseDict, ResColorDict, DispDict = {}, {}, {}, {}, {}, {}
                width, height, length, alpha, motion, D, reproduction, speciation, predators, parasites, env_gradient, seedcom, m, r, nr, rmax = get_rand_params()
                sim += 1
                alpha = np.random.uniform(0.9, 0.999)
                print '\n'

            Rates = np.roll(Rates, -1, axis=0)
            u0 = Rates[0]  # initial in-flow speed

            Ts, Rs, PRODIs, PRODQs, Ns, RESTAUs, TRACERTAUs, INDTAUs, RESDENs, RESDIVs, RESRICHs, Ss, ESs, EVs, BPs, SDs, NMAXs, SKs, MUs, MAINTs = [], [],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
            TracerTau, IndTau, ResDens, ResDiv, ResRich, S, ES, Ev, BP, SD, Nm, sk, Mu, Maint = [0,0,0,0,0,0,0,0,0,0,0,0,0,0]
            IndTimeIn, SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, IndIDs, Qs, IndExitAge = [],[],[],[],[],[],[],[]
            TracerXcoords, TracerYcoords, TracerZcoords, TracerExitAge, TracerIDs, TracerTimeIn = [],[],[],[],[],[]
            ResXcoords, ResYcoords, ResZcoords, ResIDs, ResTypes, ResExitAge, ResTimeIn, ResVals = [],[],[],[],[],[],[],[]

            if motion == 'fluid' or motion == 'conveyor':
                n0, nN, nS, nE, nW, nNE, nNW, nSE, nSW, barrier, rho, ux, uy, barrierN, barrierS, barrierE, barrierW, barrierNE, barrierNW, barrierSE, barrierSW, BarrierXcoords1, BarrierYcoords1, BarrierXcoords2, BarrierYcoords2 = LBM.SetLattice(u0, viscosity, width, height, left1, bottom1, left2, bottom2, BarrierWidth, BarrierHeight, BarrierXcoords1, BarrierYcoords1, BarrierXcoords2, BarrierYcoords2)

            if seedcom > 0:
                # inflow of resources
                ResTypes, ResVals, ResXcoords, ResYcoords, ResZcoords, ResIDs, ResID, ResTimeIn = bide.ResIn(motion, ResTypes, ResVals, ResXcoords, ResYcoords, ResZcoords, ResID, ResIDs, ResTimeIn, r, rmax, nr, width, height, length, u0, D)
                # immigration
                SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, MaintDict, GrowthDict, DispDict, SpColorDict, IDs, ID, TimeIn, Qs, ResUseDict = bide.immigration(motion, m, SpeciesIDs, IndXcoords, IndYcoords, IndZcoords, width, height, length, MaintDict, GrowthDict, DispDict, SpColorDict, IndIDs, IndID, IndTimeIn, Qs, ResUseDict, nr, u0, alpha, D)

            ####################### REPLACE ENVIRONMENT ############################
            if D == 3: ax = fig.add_subplot(111, projection='3d')
            elif D == 2: ax = fig.add_subplot(111)