示例#1
0
    def plot_profits(self, player, period):

        profits = self.results["profits"][-period:]

        plt.title("Profits")
        time_window = 100
        x = np.arange(len(profits[:, player]))
        y = []
        for i in x:
            if i < time_window:
                y_value = np.mean(profits[:i + 1, player])

            else:
                y_value = np.mean(profits[i - time_window:i + 1, player])

            y.append(y_value)

        plt.plot(x, y, color="black")
        maximum_profit = \
            self.parameters["n_positions"] * \
            self.parameters["n_prices"]
        plt.ylim(0, maximum_profit)

        plt.annotate("Time window: {}".format(time_window),
                     xy=(0.8, 0.1),
                     xycoords='axes fraction',
                     fontsize=6)

        # plt.annotate(self.string_parameters, xy=(-0.05, -0.1), xycoords='axes fraction', fontsize=6)

        plt.savefig(self.format_fig_name("profits_player{}".format(player)))
        plt.close()
示例#2
0
文件: fig17.py 项目: rschmehl/parotor
def Marzmean(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    a, b = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos)
    alpha = a
    betas = b
    Ma = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos))
    Mg = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos))
    return alpha, betas, Ma, Mg
示例#3
0
    def extract_change(data):

        move = []
        for firm in range(2):
            move.append(
                np.mean([
                    abs(data[i] - data[i + 1]) for i in range(len(data) - 1)
                ]))

        return np.mean(move)
def profits_over_fov(pool_backup, ax):

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    t_max = parameters["t_max"]

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    # Number of bins for the barplot
    n_bins = 50

    # Compute the boundaries
    boundaries = np.linspace(0, 1, (n_bins + 1))

    # Container for data
    data = [[] for i in range(n_bins)]

    for b in backups:

        r = b.parameters.r

        for i, bound in enumerate(boundaries[1:]):
            if r <= bound:
                mean_profit = np.mean(b.profits[-span:, :])
                data[i].append(mean_profit)
                break

    mean_data = [np.mean(d) for d in data]
    std_data = [np.std(d) for d in data]

    # Enhance aesthetics
    ax.set_xlim(-0.01, 1.01)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_ylim(0, 120)

    ax.tick_params(labelsize=9)

    ax.set_xlabel("$r$")
    ax.set_ylabel("Profit")

    # ax.set_title("Mean profits over $r$")

    # Do the hist plot
    width = boundaries[1] - boundaries[0]
    where = [np.mean((boundaries[i+1], boundaries[i])) for i in range(len(boundaries)-1)]
    ax.bar(where, height=mean_data, yerr=std_data, width=width,
           edgecolor='white', linewidth=2, facecolor="0.75")
示例#5
0
    def curve_plot(self, variable, t_max=5000, display=False):

        print("Doing curve plot for variable '{}'.".format(variable))

        var = Variable(name=variable)
        if var.data is None:
            self.extract_single_dimension(var, t_max=t_max)

        x = np.arange(t_max)
        mean = np.zeros(t_max)
        std = np.zeros(t_max)

        for t in range(t_max):

            mean[t] = np.mean(var.data[t])
            std[t] = np.std(var.data[t])

        plt.plot(x, mean, c='black', lw=2)
        plt.plot(x, mean + std, c='black', lw=.1)
        plt.plot(x, mean - std, c='black', lw=.1)
        plt.fill_between(x, mean + std, mean - std, color='black', alpha=.1)
        plt.xlabel("t")
        plt.ylabel(self.format_label(variable))
        plt.savefig("{}/curve_plot_{}.pdf".format(self.fig_folder, variable))
        if display:
            plt.show()
        plt.close()
示例#6
0
    def extract_single_dimension(self, variable, t_max):

        print("Extracting variable '{}'.".format(variable.name))

        if self.folders is None:
            self.get_folders()

        # noinspection PyUnusedLocal
        data = [[] for i in range(t_max)]

        for i in tqdm(self.stats.data["idx"]):

            results = Results(economy_folder=self.folders[i])
            for t in range(t_max):
                data[t].append(results.data[variable.name][t])

        print("Convert in array.")

        variable.data = dict()
        variable.data["mean"] = np.array(
            [np.mean(data[t]) for t in range(t_max)])
        variable.data["std"] = np.array(
            [np.std(data[t]) for t in range(t_max)])

        print("Write in pickle.")
        variable.write()

        print("Done.")
示例#7
0
    def compute_mean_utility(self):

        mean = np.mean(self.controller.data.current_state["customer_utility"])

        self.mean_utility.append(mean)

        self.data["customer_mean_utility"] = self.mean_utility
示例#8
0
文件: fig18.py 项目: rschmehl/parotor
def Marzmean(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    alpha, betas = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos)
    return alpha, np.mean(
        Marzsum(lK, Rg, alpha, betas, beta, delta, omegat,
                pos)), Ftrminmax(lK, Rg, alpha, betas, beta, delta, omegat,
                                 pos)
示例#9
0
def getSkeletonPositions(player):
    l = [getXyzw(player.SkeletonPositions[idd]) for idd in range(20)]+\
    [getXyzw(player.get_position())]
    sp = np.array(l)
    sp[-1, -1] = 0
    x = np.mean(sp[[jo.shoulderCenter, jo.hipCenter, jo.spine]], 0)
    sp[:-1] -= x
    return sp
示例#10
0
    def compute_mean_extra_view_choices(self):

        mean = np.mean(
            self.controller.data.current_state["customer_extra_view_choices"])

        self.mean_extra_view_choices.append(mean)

        self.data[
            "customer_mean_extra_view_choices"] = self.mean_extra_view_choices
示例#11
0
def create_fft(fn, myclass):
    try:
        sample_rate, X = scipy.io.wavfile.read(fn)
    except ValueError:
        return
    ceps, mspec, spec = mfcc(X)
    num_ceps = len(ceps)
    x = np.mean(ceps[int(num_ceps * 1 / 10):int(num_ceps * 9 / 10)], axis=0)
    y = np.int(myclass)
    XA.append(x)
    ya.append(y)
def profit_firmA_against_profit_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)
    parameters = bkp.parameters

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = np.arange(parameters.t_max)
    y = np.zeros((2, parameters.t_max))

    for f in range(2):
        for t in range(parameters.t_max):
            y[f, t] = np.mean(bkp.profits[:t + 1, f] / profit_max)

        # y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        # y_err = np.array([np.std(for_y[i][t]) for t in range(parameters.t_max)])

    fig = plt.Figure()

    plt.plot(x, y[0], label="Firm A")
    plt.plot(x, y[1], label="Firm B")
    # plt.fill_between(x, y - (y_err / 2), y + (y_err / 2), color="C{}".format(i), alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("Evolution of profits over time ($r={}$)".format(
        bkp.field_of_view / 2))

    plt.tight_layout()

    plt.savefig("{}/{}_mean_profit.pdf".format(folder, file_name))

    plt.show()
示例#13
0
文件: fig17.py 项目: rschmehl/parotor
def Marzmean0(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    return np.mean(Marzsum(lK, Rg, alpha, betas, beta, delta, omegat, pos))
def analyse_profits(pool_backup, file_name="", folder=None):
    """
    Expected running_mode is 'discrete'
    :param pool_backup:
    :param file_name:
    :param folder:
    :return:
    """

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    def f_cond(xx):
        if xx < 0.25:
            return 0
        elif xx < 0.5:
            return 1
        elif xx < 0.75:
            return 2
        else:
            return 3

    n_pools = 4
    labels = [
        "0 <= FoV < 0.25", "0.25 <= FoV < 0.50", "0.50 <= FoV < 0.75",
        "0.75 <= FoV <= 1"
    ]

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    assert backups[
        0].running_mode == "discrete", "Expected running_mode is 'discrete'"

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = range(parameters.t_max)
    for_y = [[[] for j in range(parameters.t_max)] for i in range(n_pools)]

    for i, b in tqdm.tqdm(enumerate(backups), total=len(backups)):

        cond = f_cond(b.field_of_view)

        for t in range(parameters.t_max):

            for_y[cond][t].append(np.mean(b.profits[t, :]) / profit_max)

    for i in range(n_pools):
        y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        y_err = np.array(
            [np.std(for_y[i][t]) for t in range(parameters.t_max)])
        plt.plot(x, y, label=labels[i])
        plt.fill_between(x,
                         y - (y_err / 2),
                         y + (y_err / 2),
                         color="C{}".format(i),
                         alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    if file_name:
        plt.title(file_name)

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}_mean_profit_{}_cat.pdf".format(
            folder, file_name, n_pools))

    plt.show()
示例#15
0
def distance(pool_backup, fig_name=None, ax=None):

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    n_simulations = len(parameters["seed"])
    n_positions = parameters["n_positions"]
    t_max = parameters["t_max"]

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    z = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    for i, b in enumerate(backups):

        x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(
            b.positions[-span:, 0] -
            b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)

        y[i] = spacing

        # Get std
        y_err[i] = np.std(data)

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :])

    # Plot this
    if ax is None:
        fig = plt.figure(figsize=(5, 5), dpi=200)
        ax = fig.add_subplot()

    # Enhance aesthetics
    ax.set_xlim(-0.009, 1.005)
    ax.set_ylim(-0.009, 1.005)
    # if max(y) < 0.5:
    #     ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 1.1, 0.25))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Distance")

    # ax.set_title("Mean distance between firms over $r$")

    # Display line for indicating 'random' level
    # seed = 123
    # np.random.seed(seed)
    # random_pos = np.random.random(size=(2, 10 ** 6))
    # random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1]))
    # ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1)

    # if color:
    #     _color(fig=fig, ax=ax, x=x, y=y, z=z)
    # else:
    _bw(ax=ax, x=x, y=y, y_err=y_err)

    if fig_name:
        # Cut the margins
        plt.tight_layout()

        # Create directories if not already existing
        os.makedirs(os.path.dirname(fig_name), exist_ok=True)
        # Save fig
        plt.savefig(fig_name)

        plt.close()
# Analysis
for i, voltages in enumerate(volt_list):
    timeline = voltages[:, 1]  # neuron_id, time, voltage
    membrane_voltage = voltages[:, 2]
    dVs = pylab.diff(membrane_voltage)

    print("\nInterface {}".format(i))

    # time with actual spiking activity
    spike_times = [timeline[i + 1] for i, dv in enumerate(dVs) if dv > 0]
    time_first_spike, time_last_spike = spike_times[0], spike_times[-1]
    active_time = int(time_last_spike - time_first_spike)  # ms
    # print("First spike occured at {}, last spike at {}".format(time_first_spike, time_last_spike))

    # mean spike height
    mean_decrease = np.mean([dv for dv in dVs if dv < 0])
    dv_mean = np.mean([dv - mean_decrease for dv in dVs if dv > 0
                       ])  # mean decrease per timestep needs to be added
    # because it exists even if there is a spike
    print("Mean Spike Height: {} mV".format(dv_mean))

    # expected spike height
    exp_tc = np.exp(float(-ts) / tau_m)  # time constant multiplier
    dv_expected = (tau_m / cm) * weight * (1.0 - exp_tc
                                           )  # equation for pulse input
    print("Expected Spike Height: {} mV".format(dv_expected))

    # Difference
    discrepancy = dv_expected - dv_mean
    print("Discrepancy between mean and expected: {} mV".format(discrepancy))
    # TODO Open Question: Is the discrepancy small enough and can the above formula be applied?
def profits_over_distance(file_name, folder=None, separate_A_and_B=True):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    pool_backup = backup.PoolBackup.load(file_name=file_name)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros((2, n_simulations))

    for i, b in enumerate(backups):

        # Compute the mean distance between the two firms
        data = np.absolute(b.positions[:, 0] -
                           b.positions[:, 1]) / parameters.n_positions

        spacing = np.mean(data)
        x[i] = spacing

        # Get profits
        profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value
        for f in range(2):
            y[f, i] = np.mean(b.profits[:, f]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    # ax.set_xlim(-0.01, 1.01)
    # ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    add_title_and_labels(ax)
    add_comment_with_file_name(fig=fig, file_name=file_name)

    if separate_A_and_B is True:
        ax.scatter(x, y[0], zorder=10, alpha=0.25, label="Firm A")
        ax.scatter(x, y[1], zorder=10, alpha=0.25, label="Firm B")
        add_fitting_curve(ax=ax, x=x, y=y[0])
        add_fitting_curve(ax=ax, x=x, y=y[1])
        plt.legend()

    else:
        ax.scatter(x, np.mean(y, axis=0), zorder=10, alpha=0.25, color="black")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}_profits_over_distance.pdf".format(
            folder, file_name))

    plt.show()
def distance_over_fov(pool_backup, fig_name):

    # Create directories if not already existing
    os.makedirs(os.path.dirname(fig_name), exist_ok=True)

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    n_simulations = len(parameters["seed"])
    n_positions = parameters["n_positions"]
    t_max = parameters["t_max"]

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    for i, b in enumerate(backups):

        x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(
            b.positions[-span:, 0] -
            b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :])

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    # Enhance aesthetics
    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Mean distance")

    ax.set_title("Mean distance between firms over $r$")

    # Display line for indicating 'random' level
    seed = 123
    np.random.seed(seed)
    random_pos = np.random.random(size=(2, 10 ** 6))
    random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1]))
    ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1)

    # Do the scatter plot
    scat = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)

    # Add a color bar
    fig.colorbar(scat, label="Profits")

    # Cut the margins
    plt.tight_layout()

    # Save fig
    plt.savefig(fig_name)

    plt.close()
示例#19
0
    def extract_data(self):

        print("Extract data...")

        self.stats.data = {}
        self.get_folders()

        for label in [
                "transportation_cost", "delta_position", "delta_price",
                "profits", "change_position", "change_price",
                "customer_extra_view_choices", "firm_temp", "firm_alpha",
                "customer_temp", "customer_alpha", "customer_utility",
                "customer_utility_consumption", "idx"
        ]:
            self.stats.data[label] = []

        for i, folder in tqdm(enumerate(self.folders)):

            parameters = Parameters(economy_folder=folder)
            results = Results(economy_folder=folder)

            if parameters.data is not None and results.data is not None and \
                    results.is_valid(time_window=self.time_window):
                self.stats.data["customer_utility_consumption"].append(
                    parameters.data["utility_consumption"])
                self.stats.data["transportation_cost"].append(
                    parameters.data["transportation_cost"])
                self.stats.data["firm_temp"].append(
                    parameters.data["firm_temp"])
                self.stats.data["firm_alpha"].append(
                    parameters.data["firm_alpha"])
                self.stats.data["customer_alpha"].append(
                    parameters.data["customer_alpha"])
                self.stats.data["customer_temp"].append(
                    parameters.data["customer_temp"])

                self.stats.data["delta_position"].append(
                    self.extract_delta(
                        results.data["positions"][-self.time_window:]))
                self.stats.data["delta_price"].append(
                    self.extract_delta(
                        results.data["prices"][-self.time_window:]))

                self.stats.data["customer_extra_view_choices"].append(
                    np.mean(results.data["customer_extra_view_choices"]
                            [-self.time_window:]))
                self.stats.data["profits"].append(
                    np.mean(results.data["profits"][-self.time_window:]))
                self.stats.data["customer_utility"].append(
                    np.mean(
                        results.data["customer_utility"][-self.time_window:]))

                self.stats.data["change_position"].append(
                    self.extract_change(
                        results.data["positions"][-self.time_window:]))
                self.stats.data["change_price"].append(
                    self.extract_change(
                        results.data["prices"][-self.time_window:]))

                self.stats.data["idx"].append(i)

        self.stats.write()

        print("Done.")
示例#20
0
def main(force):

    backups = backup.get_data(force)

    bins = np.arange(0, 3800, 500)

    bounds = ["{}~{}".format(i, j) for i, j in zip(bins[:-1], bins[1:])]

    fig = plt.figure(figsize=(12, 8))
    axes = fig.add_subplot(211), fig.add_subplot(212)

    for s, ax in zip((1, 0), axes):

        scores = {0.25: [], 0.5: []}

        for b in backups:

            if b.pvp and b.display_opponent_score is bool(s):
                for player in (0, 1):
                    sum_profit = np.sum(b.profits[:, player])
                    scores[b.r].append(sum_profit)

        if np.max([max(i) for i in scores.values()]) > max(bins):
            raise Exception("Max bound has been reached")

        y_upper_bound = 55

        ind = np.arange(len(bins) - 1)

        for r, color in zip((0.25, 0.50), ("C0", "C1")):

            sc = np.array(scores[r])

            print(
                "Score (r = {:.2f}, s = {}) mean: {:.2f}, std: {:.2f}, min:{}, max: {}"
                .format(r, s, np.mean(sc), np.std(sc), np.min(sc), np.max(sc)))

            d = np.digitize(sc, bins=bins)

            n = len(sc)

            y = []
            for i in ind:

                y.append(len(sc[d == i]) / n * 100)

            if np.max(y) > y_upper_bound:
                raise Exception(
                    "Max bound has been reached ({:.2f} > {})".format(
                        np.max(y), y_upper_bound))

            width = 0.35  # the width of the bars

            ax.bar(ind - width / 2 if r == 0.25 else ind + width / 2,
                   y,
                   width,
                   label='r = {:.2f}'.format(r),
                   alpha=0.5,
                   edgecolor=color)

        ax.set_xticks(ind)
        ax.set_xticklabels(bounds, fontsize=8)

        ax.set_ylim(0, y_upper_bound)

        ax.set_ylabel("Proportion (%)")

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.tick_params(length=0)
        ax.set_title('s = {}'.format(s))

    plt.tight_layout()
    plt.legend()
    plt.savefig("fig/pool_score_distribution.pdf")
    plt.show()
示例#21
0
    def extract_delta(data):

        d = np.absolute(data[:, 0] - data[:, 1])
        return np.mean(d)
示例#22
0
    def histbin(self, var1, var2):

        if var1 == "customer_extra_view_choices" and var2 == "delta_position":
            x = np.asarray(self.stats.data[var1])
            y = np.asarray(self.stats.data[var2])

            n_bin = 10

            a = np.linspace(0, 10, n_bin + 1)

            b = np.zeros(n_bin)
            for i in range(n_bin):
                yo = list()
                for idx, xi in enumerate(x):
                    if a[i] <= xi < a[i + 1]:
                        yo.append(y[idx])

                b[i] = np.median(yo) if len(yo) else 0

            # ----- #

            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)

            plt.xlim(self.range_var[var1])
            plt.ylim(self.range_var[var2])

            plt.xlabel(self.format_label(var1))
            plt.ylabel(self.format_label(var2))

            ax.bar(a[:-1] + (a[1] - a[0]) / 2, b, a[1] - a[0], color='grey')

            plt.savefig("{}/hist_median_{}_{}.pdf".format(
                self.fig_folder, var1, var2))

            # --- #

            if self.display:
                plt.show()

            plt.close()

            # ---- #

            b = np.zeros(n_bin)
            c = np.zeros(n_bin)
            for i in range(n_bin):
                yo = list()
                for idx, xi in enumerate(x):
                    if a[i] <= xi < a[i + 1]:
                        yo.append(y[idx])

                b[i] = np.mean(yo) if len(yo) else 0
                c[i] = np.std(yo) if len(yo) else 0

            # ----- #

            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)

            plt.xlim(self.range_var[var1])
            plt.ylim(self.range_var[var2])

            plt.xlabel(self.format_label(var1))
            plt.ylabel(self.format_label(var2))

            ax.bar(a[:-1] + (a[1] - a[0]) / 2,
                   b,
                   a[1] - a[0],
                   color='grey',
                   yerr=c)

            plt.savefig("{}/hist_mean_{}_{}.pdf".format(
                self.fig_folder, var1, var2))

            # --- #

            if self.display:
                plt.show()

            plt.close()
def distance_over_fov(file_name, pool_backup, fig_folder=None):

    span_ratio = 0.33

    if fig_folder is None:
        fig_folder = "data/figures"

    os.makedirs(fig_folder, exist_ok=True)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    n_positions = parameters.n_positions
    p_max = parameters.p_max

    # Compute profit max
    profit_max = n_positions * p_max

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span = int(span_ratio * parameters.t_max)

    for i, b in enumerate(backups):

        try:
            # Save the parameter that affected the customers field of view
            x[i] = b.field_of_view / 2
        except AttributeError:
            x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(b.positions[-span:, 0] -
                           b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Mean distance")

    ax.set_title("Mean distance between firms over $r$")

    # add comment with file name
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    # show random
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)
    fig.colorbar(abc, label="Profits")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}.pdf".format(fig_folder, file_name))

    plt.show()
def distance_over_fov(file_name, show_random=True, bw=False, show_error_bars=False, show_fitting_curve=False,
                      fig_folder=None, data_folder=None):

    if fig_folder is None:
        fig_folder = "data/figures"

    os.makedirs(fig_folder, exist_ok=True)

    pool_backup = backup.PoolBackup.load(folder_name=data_folder, file_name=file_name)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    n_positions = parameters.n_positions
    n_prices = parameters.n_prices
    unit_value = parameters.unit_value

    # Compute profit max
    profit_max = n_positions * n_prices * unit_value

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span = int(span_ratio * parameters.t_max)

    for i, b in enumerate(backups):

        try:
            # Save the parameter that affected the customers field of view
            x[i] = b.field_of_view / 2
        except AttributeError:
            x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(
                b.positions[-span:, 0] -
                b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    add_title_and_labels(ax)
    add_comment_with_file_name(fig=fig, file_name=file_name)

    if show_random:
        ax.axhline(0.33, color='0.5', linewidth=0.5, linestyle="--", zorder=-10)

    if show_error_bars:
        ax.errorbar(x, y, yerr=y_err, fmt='.', alpha=0.1)

    if show_fitting_curve:
        add_fitting_curve(ax=ax, x=x, y=y)

    if hasattr(parameters, 'running_mode') and parameters.running_mode == "discrete":
        boxplot(pool_backup=pool_backup, ax=ax, y=y)

    if bw:
        plot_bw(ax=ax, x=x, y=y, file_name=file_name, fig_folder=fig_folder)

    else:
        plot_color(fig=fig, ax=ax, x=x, y=y, z=z, file_name=file_name, fig_folder=fig_folder)