Ejemplo n.º 1
0
def genStackPlotvsTimeGraph(filename, numTimeStep, filterList=None):
    """Generates a stack plot of prey states over time step for Intention and 
    non intention modes. NOTE: Will probably need to include cautiousness
    as another graph later.
    NOTE: Requires the last dataframe in dataframes to be the one that makes prey die the fastest
    Inputs:
        filename: the name of the csv file to read from
        numTimeStep: the time for which the prey can go without eating before
        dying of hunger.
        filterList: a filter list to filter the runs by. Most likely use if 
            we need to filter to only get the standard seed from a csv with 
            varied parameters. eg. [["predSightDistance", 10]]"""
    modes, dfs = getPerceptionTierDataframes(filename)

    plt.rc('font', family='serif')
    fig, axes = plt.subplots(1, 3)
    fig.tight_layout(w_pad=1, h_pad=1, rect=[0, 0, .9, .9])
    fig.suptitle("Prey Status over Time", fontsize=16)
    axs = axes.flat
    plt.style.use('ggplot')
    colorList = ['#4FADAC', '#5386A6', '#2F5373']

    maxX = 0  # initialize. This will be set later and will make all x axes the same.

    graphInfo = []

    # loop through dataframes. We will want one stackplot per mode.
    for perceptionNum in range(len(dfs)):
        perceptionDf = dfs[perceptionNum]
        # filter
        if filterList != None:
            perceptionDf = ds.filterDataFrame(perceptionDf, filterList)
        aliveOverTime, eatenOverTime, starvedOverTime = helpStackPlot(
            perceptionDf, numTimeStep)
        graphInfo.append([aliveOverTime, starvedOverTime, eatenOverTime])

    maxX = calcMaxX(graphInfo)

    for perceptionNum in range(len(dfs)):
        # x-list is timestep
        x_list = range(maxX)

        axs[perceptionNum].set_title(modes[perceptionNum], fontsize=12)
        axs[perceptionNum].set_ylabel("Average Number of Prey", fontsize=10)
        axs[perceptionNum].set_xlabel("Timestep of Simulation", fontsize=10)
        axs[perceptionNum].tick_params(axis='both',
                                       which='major',
                                       labelsize=9,
                                       direction='in')
        axs[perceptionNum].set(ylim=(0, 20), xlim=(0, maxX))

        plt.sca(axs[perceptionNum])
        yList1 = extendList(graphInfo[perceptionNum][0][:maxX], maxX)
        yList2 = extendList(graphInfo[perceptionNum][1][:maxX], maxX)
        yList3 = extendList(graphInfo[perceptionNum][2][:maxX], maxX)

        plt.stackplot(x_list, yList1, yList2, yList3, colors=colorList)
    fig.legend(labels=["Alive", "Starved", "Eaten"])
    plt.rc('text', usetex=True)
    plt.show()
Ejemplo n.º 2
0
def getPerceptionTierDataframes(filename):
    """Takes in a csv file and returns data frames according to perception tiers 
    Inputs:
        filename: String, the name of the csv file to read from"""
    data = pd.read_csv(filename)
    df0 = ds.filterDataFrame(
        data, [["targetedAware", True], ["proximityAware", True]])
    df1 = ds.filterDataFrame(
        data, [["targetedAware", False], ["proximityAware", True]])
    df2 = ds.filterDataFrame(
        data, [["targetedAware", False], ["proximityAware", False]])
    dfs = [df0, df1, df2]
    modes = [
        r"Proximity and Attention Awareness", r"Only Proximity Awareness",
        r"No Awareness"
    ]
    return modes, dfs
Ejemplo n.º 3
0
def getPerceptionDataframesCaution(filename, cfilename):
    """New version of getPerceptionTierDataframes() that includes the caution mode.
    Inputs:
        filename: the filename to read from"""
    data = pd.read_csv(filename)
    df0 = ds.filterDataFrame(
        data, [["targetedAware", True], ["proximityAware", True]])
    df1 = ds.filterDataFrame(
        data, [["targetedAware", False], ["proximityAware", True]])
    df2 = ds.filterDataFrame(
        data, [["targetedAware", False], ["proximityAware", False]])
    df3 = pd.read_csv(cfilename)

    dfs = [df0, df1, df2, df3]
    modes = [
        r"Proximity + Attention", r"Proximity Only", r"Unaware", r"Cautious"
    ]
    return modes, dfs
Ejemplo n.º 4
0
def getCautiousSeedData(filename, newfilename, param):
    data = pd.read_csv(filename)
    df = hd.filterDataFrame(data, [["targetedAware", True], ["proximityAware", True]])
    paramDict = {}
    for val, group in df.groupby(param):
        groupProbs = []
        groupLengths = []
        for _, run in group.iterrows():
            probs, lengths = ast.literal_eval(run["targetInfo"])
            groupProbs += probs
            groupLengths += lengths
        avg, _, _ = hd.listStats(groupProbs)
        paramDict[str(val)] = [avg, groupLengths]
    with open(newfilename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(["keys", "values"])
        for key, value in paramDict.items():
            writer.writerow([key, value])
Ejemplo n.º 5
0
def hungerGraph(filename, cautiousFile=None):

    labelsize = 18
    legendsize = 14
    titlesize = 20
    ticksize = 16

    data = pd.read_csv(filename)
    plt.style.use('ggplot')
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
        
    df0 = hd.filterDataFrame(data, [["targetedAware", True], ["proximityAware", True], ["predSightAngle", 90]])
    df1 = hd.filterDataFrame(data, [["targetedAware", False], ["proximityAware", True], ["predSightAngle", 90]])
    df2 = hd.filterDataFrame(data, [["targetedAware", False], ["proximityAware", False], ["predSightAngle", 90]])

    dfs = [df0, df1, df2]
    modes = [r"Proximity + Attention", r"Proximity Only", r"Unaware"]

    colorIter = iter(['#4FADAC', '#5386A6', '#2F5373', '#C59CE6'])

    intention_list = []
    proximity_list = []
    unaware_list = []
    all_lists = [intention_list, proximity_list, unaware_list]

    if cautiousFile:
        dfs.append(pd.read_csv(cautiousFile))
        modes.append(r"Cautious")
        cautious_list = []
        all_lists.append(cautious_list)

    fig = plt.figure(figsize=(5,5))
    
    x = [step for step in range(1, 10000+2, 500)]
    for n_steps in x:
        print("step:",n_steps)
        for i in range(3 + (cautiousFile != None)):
            df = dfs[i]
            groupLifeTimes = []
            for _, run in df.iterrows():
                counts = run["preyCountOverTime"]
                foodPerPrey = run["foodPerPrey"]
                preyPerPred = run["preyPerPred"]
                revisedCounts, _ = h.getNewPreyCountOverTimeList(foodPerPrey, counts, preyPerPred, n_steps)
                lifetimes = hd.lifeTimes(revisedCounts)
                groupLifeTimes += lifetimes
            avg, _, ci = hd.listStats(groupLifeTimes)
            all_lists[i].append([avg, ci[0], ci[1]])

    for i in range(len(all_lists)):
        tier = all_lists[i]
        val = []
        l_ci = []
        u_ci = []
        for point in tier:
            a, lc, uc = point
            val.append(a)
            l_ci.append(lc)
            u_ci.append(uc)
        
        color = next(colorIter)
        fig.gca().plot(x, val, label=modes[i], color=color, linewidth=2)
        fig.gca().fill_between(x, l_ci, u_ci, color=color, alpha=.15)
    
    ax = fig.gca()
    ax.set(ylim=(0, 10000), xlim=(0,10000-1))
    ax.set_ylabel(r"prey lifespan (time steps)", fontsize=labelsize, fontweight='bold')
    ax.set_xlabel(r"maximum fasting interval (time steps)", fontsize=labelsize, fontweight='bold')
    ax.tick_params(axis='both', which='major', labelsize=ticksize, direction='in')
    plt.legend(prop={"size":legendsize})
    plt.title(r"Maximum Fasting Interval", fontsize=titlesize, fontweight='bold')
    fig.savefig("hunger.pdf", bbox_inches='tight', pad_inches=0)
    plt.close('all')
Ejemplo n.º 6
0
def linearRunGraph(filename, param, n_steps, cautiousFile=None):
    labelsize = 18
    legendsize = 14
    titlesize = 20
    ticksize = 16

    data = pd.read_csv(filename)
    plt.style.use('ggplot')
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
        
    df0 = hd.filterDataFrame(data, [["targetedAware", True], ["proximityAware", True]])
    df1 = hd.filterDataFrame(data, [["targetedAware", False], ["proximityAware", True]])
    df2 = hd.filterDataFrame(data, [["targetedAware", False], ["proximityAware", False]])

    dfs = [df0, df1, df2]

    modes = [r"Proximity + Attention", r"Proximity Only", r"Unaware"]

    if cautiousFile:
        df3 = pd.read_csv(cautiousFile)
        dfs.append(df3)
        modes.append(r"Cautious")

    colorIter = iter(['#4FADAC', '#5386A6', '#2F5373', '#C59CE6'])
    
    fig = plt.figure(figsize=(5,5))

    for i in range(3 + (cautiousFile != None)):
        df = dfs[i]
        paramValues = []
        survival = []
        up_ci = []
        low_ci = []

        for val, group in df.groupby(param):
            groupLifeTimes = []
            for _, run in group.iterrows():
                counts = run["preyCountOverTime"]
                foodPerPrey = run["foodPerPrey"]
                preyPerPred = run["preyPerPred"]
                revisedCounts, _ = h.getNewPreyCountOverTimeList(foodPerPrey, counts, preyPerPred, n_steps)
                lifetimes = hd.lifeTimes(revisedCounts)
                groupLifeTimes += lifetimes
            
            avg, _, ci = hd.listStats(groupLifeTimes)

            paramValues.append(val)
            survival.append(avg)
            low_ci.append(ci[0])
            up_ci.append(ci[1])

        color = next(colorIter)
        plt.plot(paramValues, survival, label=modes[i], color=color, linewidth=2)
        plt.fill_between(paramValues, low_ci, up_ci, color=color, alpha=.15)
    
    global labels
    ax = fig.gca()
    ax.set(ylim=(0, 10000))
    ax.set_ylabel(r"prey lifespan (time steps)", fontsize=labelsize, fontweight='bold')
    ax.set_xlabel(r""+ labels[param][1], fontsize=labelsize, fontweight='bold')
    ax.tick_params(axis='both', which='major', labelsize=ticksize, direction='in')
    plt.legend(prop={"size":legendsize})
    plt.title(r"" + labels[param][0], fontsize=titlesize, fontweight='bold')
    fig.tight_layout()
    fig.savefig(param + '.pdf', bbox_inches='tight', pad_inches=0)
    plt.close('all')
Ejemplo n.º 7
0
def genNewStackPlotvsTimeGraph(filename,
                               numTimeStep,
                               filterList=None,
                               cfilename=None):
    """Generates separate stack plots of prey states over time step for intention and 
    non intention modes. Includes an option to make a stackplot for the caution mode.

    Inputs:
        filename: String, the name of the csv file to read from
        numTimeStep: Int, the time for which the prey can go without eating before
        dying of hunger.
        filterList: List, a filter list to filter the runs by. Most likely use if 
            we need to filter to only get the standard seed from a csv with 
            varied parameters. eg. [["predSightDistance", 10]]"""

    labelsize = 18
    legendsize = 14
    titlesize = 20
    ticksize = 16

    # Determine whether the "Cautious" stackplot should be made.
    if cfilename:
        modes, dfs = getPerceptionDataframesCaution(filename, cfilename)
    else:
        modes, dfs = getPerceptionTierDataframes(filename)

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.style.use('ggplot')
    colorList = ['#4FADAC', '#5386A6', '#2F5373']

    maxX = 0  # Initialize. This will be set later and will make all x axes the same.

    graphInfo = []

    # loop through dataframes. We will want one stackplot per mode.
    for perceptionNum in range(len(dfs)):
        perceptionDf = dfs[perceptionNum]
        # filter
        if filterList != None:
            perceptionDf = ds.filterDataFrame(perceptionDf, filterList)
        aliveOverTime, eatenOverTime, starvedOverTime = helpStackPlot(
            perceptionDf, numTimeStep)
        graphInfo.append([aliveOverTime, starvedOverTime, eatenOverTime])

    maxX = calcMaxX(graphInfo)

    for perceptionNum in range(len(dfs)):

        fig = plt.figure(figsize=[5, 5])

        axs = fig.gca()

        # x-list is timestep
        x_list = range(maxX)

        axs.set_title("" + modes[perceptionNum],
                      fontsize=titlesize,
                      fontweight='bold')
        axs.set_ylabel("" + "Average Number of Prey",
                       fontsize=labelsize,
                       fontweight='bold')
        axs.set_xlabel("" + "Timestep of Simulation",
                       fontsize=labelsize,
                       fontweight='bold')
        axs.tick_params(axis='both',
                        which='major',
                        labelsize=ticksize,
                        direction='in')
        axs.set(ylim=(0, 20), xlim=(0, maxX))

        yList1 = extendList(graphInfo[perceptionNum][0][:maxX], maxX)
        yList2 = extendList(graphInfo[perceptionNum][1][:maxX], maxX)
        yList3 = extendList(graphInfo[perceptionNum][2][:maxX], maxX)
        plt.stackplot(x_list, yList1, yList2, yList3, colors=colorList)
        plt.legend(labels=["Alive", "Starved", "Eaten"],
                   prop={"size": legendsize})
        fig.tight_layout()
        fig.savefig("hungerstack" + str(perceptionNum) + '.pdf',
                    bbox_inches='tight',
                    pad_inches=0)
    plt.close('all')