def general_plot(bkup, strategies): fig = plt.figure(figsize=(8, 5)) nrows = 2 ncols = 2 gs = matplotlib.gridspec.GridSpec(nrows, ncols) axes = [ fig.add_subplot(gs[x, y]) for x in range(nrows) for y in range(ncols) ] display_score = ( False, True, ) * ncols radius = (0.25, ) * ncols + (0.5, ) * ncols for ax, r, s in zip(axes, radius, display_score): data = [ bkup.fit_scores[(bkup.r == r) * (bkup.display_opponent_score == s)][:, strategy] for strategy in sorted(strategies.keys()) ] color = [ "C{}".format(strategy + 1) for strategy in sorted(strategies.keys()) ] ax.set_ylim(0, 1) ax.set_title("r = {:.2f}, s = {}".format(r, int(s))) customized_plot.violin(ax=ax, data=data, color=color, alpha=0.8) for ax in axes[2:]: labels = [] for k in sorted(strategies.keys()): if "competition" in strategies[k]: labels.append("{}\nvs\n{}".format(*strategies[k]).replace( "competition", "distance")) else: labels.append("{}\nvs\n{}".format(*strategies[k])) ax.set_xticklabels(labels) ax.tick_params(length=0) for ax in axes[:2]: ax.set_xticks([]) for ax in axes[::2]: ax.set_ylabel("Score") plt.tight_layout() plt.show()
def scores_distribution(data, subplot_spec): n_rows, n_cols = 2, 2 gs = matplotlib.gridspec.GridSpecFromSubplotSpec(nrows=n_rows, ncols=n_cols, subplot_spec=subplot_spec) positions = it.product(range(2), repeat=2) scores_to_plot = ["profit", "competition", "equal_sharing"] # fit.Score.names n_dim = len(scores_to_plot) colors = ["C{}".format(i + 2) for i in range(n_dim)] axes = [] for d in data: pos = next(positions) ax = plt.subplot(gs[pos[0], pos[1]]) customized_plot.violin(data=d, ax=ax, color=colors, alpha=0.8) ax.set_ylim(0, 1) ax.set_yticks(np.arange(0, 1.1, 0.25)) ax.tick_params(labelsize=8, axis="y") ax.tick_params(length=0, axis='x') axes.append(ax) for i, ax in enumerate(axes[:-2]): ax.set_title(["$s = 0$", "$s = 1$"][i], fontsize=14) ax.set_xticklabels([]) for ax in axes[-2:]: ax.set_xticklabels( ["Profit\nmax.", "Difference\nmax.", "Tacit\ncollusion"]) for ax in axes[1::2]: ax.set_yticklabels([]) ax.tick_params(length=0, axis="y") for i, ax in enumerate(axes[0::2]): ax.text(-0.32, 0.5, ["$r = 0.25$", "$r = 0.50$"][i], rotation="vertical", verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, fontsize=14) ax.set_ylabel("\nScore")
def plot_violin_with_dashed_mean(force): backups = backup.get_data(force) # ----------------- Data ------------------- # # Look at the parameters n_simulations = len(backups) n_positions = backups[0].n_positions # Containers d = np.zeros(n_simulations) prices = np.zeros(n_simulations) scores = np.zeros(n_simulations) r = np.zeros(n_simulations) s = np.zeros(n_simulations, dtype=bool) for i, b in enumerate(backups): # Compute the mean distance between the two firms data = np.absolute( b.positions[:, 0] - b.positions[:, 1]) / n_positions d[i] = np.mean(data) # Compute the mean price prices[i] = np.mean(b.prices[:, :]) # Compute the mean profit scores[i] = np.mean(b.profits[:, :]) r[i] = b.r s[i] = b.display_opponent_score # ---------- Plot ----------------------------- # fig = plt.figure(figsize=(8, 4)) sub_gs = matplotlib.gridspec.GridSpec(nrows=1, ncols=2) axes = ( fig.add_subplot(sub_gs[0, 0]), fig.add_subplot(sub_gs[0, 1]), ) s_values = (0, 1) r_values = (0.25, 0.5) arr = (scores, scores) mean_025_profit, mean_05_profit = _get_bot_mean_profits("profit", "profit") mean_025_comp, mean_05_comp = _get_bot_mean_profits("competition", "competition") arr_mean_profit = ((mean_025_profit, mean_05_profit), ) * 2 arr_mean_comp = ((mean_025_comp, mean_05_comp), ) * 2 xmins = (0.02, 0.6) xmaxs = (0.4, 0.98) plt.text(0.01, 140, "Display opponent score", fontsize=12) axes[0].set_title("\n\nFalse") axes[1].set_title("True") for idx in range(len(axes)): ax = axes[idx] ax.set_axisbelow(True) ax.set_ylim(0, 120) ax.set_ylabel("Score") ax.set_xticklabels(r_values) for i in range(2): ax.axhline(arr_mean_profit[idx][i], color='green', linewidth=1.2, linestyle="--", label="Profit-based" if i == 0 else None, zorder=1, xmin=xmins[i], xmax=xmaxs[i]) for i in range(2): ax.axhline(arr_mean_comp[idx][i], color='red', linewidth=1.2, linestyle="--", label="Competition-based" if i == 0 else None, zorder=1, xmin=xmins[i], xmax=xmaxs[i]) ax.legend() data = [arr[idx][(r == r_value) * (s == s_values[idx])] for r_value in (0.25, 0.50)] color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)] customized_plot.violin(ax=ax, data=data, color=color, edgecolor=color, alpha=0.5) plt.tight_layout() plt.show()
def all_plot(backups, strategies, reversed_strategies): # ----------------- Data ------------------- # # Look at the parameters n_simulations = len(backups) n_positions = 21 # Containers d = np.zeros(n_simulations) prices = np.zeros(n_simulations) scores = np.zeros(n_simulations) r = np.zeros(n_simulations) p = np.zeros(n_simulations, dtype=int) for i, b in enumerate(backups): # Compute the mean distance between the two firms data = np.absolute( b.positions[:, 0] - b.positions[:, 1]) / n_positions d[i] = np.mean(data) # Compute the mean price prices[i] = np.mean(b.prices[:, :]) # Compute the mean profit scores[i] = np.mean(b.profits[:, :]) r[i] = b.r p[i] = reversed_strategies[b.p_strategy] # ---------- Plot ----------------------------- # fig = plt.figure(figsize=(25, 13)) y_labels = "Distance", "Price", "Score" ncols = len(strategies) nrows = len(y_labels) sub_gs = matplotlib.gridspec.GridSpec(nrows=nrows, ncols=ncols) axes = [ fig.add_subplot(sub_gs[x, y]) for x in range(nrows) for y in range(ncols) ] y_limits = ((0, 1), ) * ncols + ((0.9, 11.1), ) * ncols + ((0, 120), ) * ncols arr = (d, ) * ncols + (prices, ) * ncols + (scores, ) * ncols strategies_to_display = tuple(range(ncols)) * nrows for idx in range(len(axes)): ax = axes[idx] ax.set_axisbelow(True) # Violin plot data = [arr[idx][(r == r_value) * (p == strategies_to_display[idx])] for r_value in (0.25, 0.50)] color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)] customized_plot.violin(ax=ax, data=data, color=color, edgecolor=color, alpha=0.5) for ax, y_lim in zip(axes, y_limits): ax.set_ylim(y_lim) for ax in (axes[:-6]): ax.set_xticklabels([]) ax.tick_params(axis="x", length=0) for ax in axes[-6:]: ax.set_xticklabels(["{:.2f}".format(i) for i in (0.25, 0.50)]) ax.set_xlabel("r") for i, y_label in zip(range(0, len(axes), ncols), y_labels): axes[i].set_ylabel(y_label) for ax in axes[i + 1 : i + 6]: ax.tick_params(length=0, axis="y") ax.set_yticklabels([]) for ax, title in zip(axes[:ncols], strategies.values()): ax.set_title("{} VS {}".format(title[0].capitalize(), title[1].capitalize())) plt.tight_layout() plt.savefig("fig/simulation_all.pdf") plt.show()
def individual_plot(backups, p0_strategy, p1_strategy): # ----------------- Data ------------------- # # Look at the parameters n_simulations = len(backups) n_positions = 21 # Containers d = np.zeros(n_simulations) prices = np.zeros(n_simulations) scores = np.zeros(n_simulations) r = np.zeros(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]) / n_positions d[i] = np.mean(data) # Compute the mean price prices[i] = np.mean(b.prices[:, :]) # Compute the mean profit scores[i] = np.mean(b.profits[:, :]) r[i] = b.r # ---------- Plot ----------------------------- # fig = plt.figure(figsize=(4, 7)) sub_gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=1) axes = ( fig.add_subplot(sub_gs[0, 0]), fig.add_subplot(sub_gs[1, 0]), fig.add_subplot(sub_gs[2, 0]), ) y_labels = "Distance", "Price", "Score" y_limits = (0, 1), (0.9, 11.1), (0, 120) arr = (d, prices, scores) for idx in range(len(axes)): ax = axes[idx] ax.set_axisbelow(True) # Violin plot data = [arr[idx][r == r_value] for r_value in (0.25, 0.50)] color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)] customized_plot.violin(ax=ax, data=data, color=color, edgecolor=color, alpha=0.5) axes[-1].set_xticklabels(["{:.2f}".format(i) for i in (0.25, 0.50)]) axes[-1].set_xlabel("r") for ax in (axes[:-1]): ax.set_xticklabels([]) ax.tick_params(axis="x", length=0) for ax, y_label, y_lim in zip(axes[:], y_labels, y_limits): ax.set_ylabel(y_label) ax.set_ylim(y_lim) plt.tight_layout() plt.savefig("fig/simulation_{}_{}.pdf".format(p0_strategy, p1_strategy)) plt.show()
def main(force): backups = backup.get_data(force) backups = [b for b in backups if b.pvp] # ----------------- Data ------------------- # # Look at the parameters n_simulations = len(backups) n_positions = backups[0].n_positions # Containers d = np.zeros(n_simulations) prices = np.zeros(n_simulations) scores = np.zeros(n_simulations) r = np.zeros(n_simulations) s = np.zeros(n_simulations, dtype=bool) for i, b in enumerate(backups): # Compute the mean distance between the two firms data = np.absolute(b.positions[:, 0] - b.positions[:, 1]) / n_positions d[i] = np.mean(data) # Compute the mean price prices[i] = np.mean(b.prices[:, :]) # Compute the mean profit scores[i] = np.mean(b.profits[:, :]) r[i] = b.r s[i] = b.display_opponent_score # ---------- Plot ----------------------------- # fig = plt.figure(figsize=(4, 7), dpi=200) sub_gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=2) axes = (fig.add_subplot(sub_gs[0, 0]), fig.add_subplot(sub_gs[0, 1]), fig.add_subplot(sub_gs[1, 0]), fig.add_subplot(sub_gs[1, 1]), fig.add_subplot(sub_gs[2, 0]), fig.add_subplot(sub_gs[2, 1])) y_labels = "Distance", "Price", "Profit" y_limits = (0, 1), (1, 11), (0, 120) s_values = ( 0, 1, ) * 3 arr = (d, d, prices, prices, scores, scores) # axes[0].text(2, 1.3, "Display opponent score", fontsize=12) axes[0].set_title("$s = 0$") axes[1].set_title("$s = 1$") for idx in range(len(axes)): ax = axes[idx] ax.set_axisbelow(True) # Violin plot data = [ arr[idx][(r == r_value) * (s == s_values[idx])] for r_value in (0.25, 0.50) ] color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)] customized_plot.violin(ax=ax, data=data, color=color, edgecolor="white", alpha=0.8) # color, alpha=0.5) for ax in axes[0:2]: ax.set_yticks(np.arange(0, 1.1, 0.25)) for ax in axes[2:4]: ax.set_yticks(np.arange(1, 11.1, 2)) for ax in axes[-2:]: ax.set_xticklabels(["{:.2f}".format(i) for i in (0.25, 0.50)]) ax.set_xlabel("$r$") for ax in axes[:4]: ax.tick_params(length=0, axis="x") ax.set_xticklabels([]) for ax, y_label, y_lim in zip(axes[0::2], y_labels, y_limits): ax.text(-0.35, 0.5, y_label, rotation="vertical", verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.set_ylabel(" ") ax.tick_params(axis="y", labelsize=9) ax.set_ylim(y_lim) for ax, y_lim in zip(axes[1::2], y_limits): ax.set_ylim(y_lim) ax.tick_params(length=0, axis="y") ax.set_yticklabels([]) plt.tight_layout() plt.savefig("fig/main_exp.pdf") plt.show() # ----------- Stats ----------------- # to_compare = [{ "measure": "distance", "constant": "s = 0", "var": "r", "data": [d[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)] }, { "measure": "distance", "constant": "s = 1", "var": "r", "data": [d[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)] }, { "measure": "price", "constant": "s = 0", "var": "r", "data": [prices[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)] }, { "measure": "price", "constant": "s = 1", "var": "r", "data": [prices[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)] }, { "measure": "profit", "constant": "s = 0", "var": "r", "data": [scores[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)] }, { "measure": "profit", "constant": "s = 1", "var": "r", "data": [scores[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)] }, { "measure": "distance", "constant": "r = 0.25", "var": "s", "data": [d[(r == 0.25) * (s == s_value)] for s_value in (0, 1)] }, { "measure": "distance", "constant": "r = 0.50", "var": "s", "data": [d[(r == 0.50) * (s == s_value)] for s_value in (0, 1)] }, { "measure": "price", "constant": "r = 0.25", "var": "s", "data": [prices[(r == 0.25) * (s == s_value)] for s_value in (0, 1)] }, { "measure": "price", "constant": "r = 0.50", "var": "s", "data": [prices[(r == 0.50) * (s == s_value)] for s_value in (0, 1)] }, { "measure": "profit", "constant": "r = 0.25", "var": "s", "data": [scores[(r == 0.25) * (s == s_value)] for s_value in (0, 1)] }, { "measure": "profit", "constant": "r = 0.50", "var": "s", "data": [scores[(r == 0.50) * (s == s_value)] for s_value in (0, 1)] }] ps = [] us = [] for dic in to_compare: u, p = scipy.stats.mannwhitneyu(dic["data"][0], dic["data"][1]) ps.append(p) us.append(u) valid, p_corr, alpha_c_sidak, alpha_c_bonf = \ statsmodels.stats.multitest.multipletests(pvals=ps, alpha=0.01, method="b") for p, u, p_c, v, dic in zip(ps, us, p_corr, valid, to_compare): print( "[Diff in {} when {} depending on {}-value] " "Mann-Whitney rank test: u {}, p {:.3f}, p corr {:.3f}, significant: {}" .format(dic["measure"], dic["constant"], dic["var"], u, p, p_c, v)) print() table = \ r"\begin{table}[htbp]" + "\n" + \ r"\begin{center}" + "\n" + \ r"\begin{tabular}{llllllll}" + "\n" + \ r"Measure & Variable & Constant & $u$ & $p$ (before corr.) " \ r"& $p$ (after corr.) & Sign. at 1\% threshold \\" + "\n" + \ r"\hline \\" + "\n" for p, u, p_c, v, dic in zip(ps, us, p_corr, valid, to_compare): p = "{:.3f}".format(p) if p >= 0.001 else "$<$ 0.001" p_c = "{:.3f}".format(p_c) if p_c >= 0.001 else "$<$ 0.001" v = "yes" if v else "no" table += r"{} & ${}$ & ${}$ & {} & {} & {} & {} \\"\ .format(dic["measure"], dic["var"], dic["constant"], u, p, p_c, v) \ + "\n" table += \ r"\end{tabular}" + "\n" + \ r"\end{center}" + "\n" + \ r"\caption{Significance tests for comparison using Mann-Withney's u. " \ r"Bonferroni corrections are applied.}" + "\n" + \ r"\label{table:significance_tests}" + "\n" + \ r"\end{table}" print("*** Latex-formated table ***") print(table)
def plot(data, subplot_spec): r, s, dist, prices, scores = data gs = matplotlib.gridspec.GridSpecFromSubplotSpec(nrows=3, ncols=2, subplot_spec=subplot_spec) axes = (plt.subplot(gs[0, 0]), plt.subplot(gs[0, 1]), plt.subplot(gs[1, 0]), plt.subplot(gs[1, 1]), plt.subplot(gs[2, 0]), plt.subplot(gs[2, 1])) y_labels = "Distance", "Price\n", "Profit\n" y_limits = (0, 1), (1, 11), (0, 120) s_values = ( 0, 1, ) * 3 arr = (dist, dist, prices, prices, scores, scores) # axes[0].text(2, 1.3, "Display opponent score", fontsize=12) axes[0].set_title("$s = 0$") axes[1].set_title("$s = 1$") for idx in range(len(axes)): ax = axes[idx] ax.set_axisbelow(True) # Violin plot data = [ arr[idx][(r == r_value) * (s == s_values[idx])] for r_value in (0.25, 0.50) ] color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)] customized_plot.violin(ax=ax, data=data, color=color, edgecolor="white", alpha=0.8) # color, alpha=0.5) for ax in axes[0:2]: ax.set_yticks(np.arange(0, 1.1, 0.25)) for ax in axes[2:4]: ax.set_yticks(np.arange(1, 11.1, 2)) for ax in axes[-2:]: ax.set_xticklabels(["{:.2f}".format(i) for i in (0.25, 0.50)]) ax.set_xlabel("$r$") for ax in axes[:4]: ax.tick_params(length=0, axis="x") ax.set_xticklabels([]) for ax, y_label, y_lim in zip(axes[0::2], y_labels, y_limits): ax.text(-0.35, 0.5, y_label, rotation="vertical", verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.set_ylabel(y_label) ax.tick_params(axis="y", labelsize=9) ax.set_ylim(y_lim) for ax, y_lim in zip(axes[1::2], y_limits): ax.set_ylim(y_lim) ax.tick_params(length=0, axis="y") ax.set_yticklabels([])