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()
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.")
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")
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()
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, 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)
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()
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()
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()
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()