def plot(cls, suffix, data_folder=None, multi=0): if data_folder: parameters, direct_exchange, indirect_exchange = import_data(suffix=suffix, data_folder=data_folder) else: parameters, direct_exchange, indirect_exchange = import_data(suffix=suffix) if multi: nb_list = len(indirect_exchange) t_max = len(indirect_exchange[0]) agents_proportions = np.zeros((t_max, 3)) for i in range(nb_list): for k in range(t_max): for j in range(3): agents_proportions[k, j] = direct_exchange[i][k][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix) else: t_max = len(indirect_exchange) agents_proportions = np.zeros((t_max, 3)) for i in range(t_max): for j in range(3): agents_proportions[i, j] = indirect_exchange[i][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix, parameters=parameters)
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 plot(cls, suffix, multi=1): parameters, direct_exchange, indirect_exchange = import_data(suffix=suffix) if multi: nb_list = len(direct_exchange) t_max = len(direct_exchange[0]) agents_proportions = np.zeros((t_max, 3)) for i in range(nb_list): for k in range(t_max): for j in range(3): agents_proportions[k, j] = direct_exchange[i][k][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix) else: t_max = len(direct_exchange) agents_proportions = np.zeros((t_max, 3)) for i in range(t_max): for j in range(3): agents_proportions[i, j] = direct_exchange[i][str(j)] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix)
def add_fitting_curve(ax, x, y): from scipy.optimize import least_squares def model(x, u): return x[0] * (u**2 + x[1] * u) / (u**2 + x[2] * u + x[3]) def fun(x, u, y): return model(x, u) - y order = np.argsort(x) xdata = x[order] ydata = y[order] x0 = np.zeros(4) res = least_squares(fun, x0, bounds=(-1, 100), args=(xdata, ydata), verbose=1).x u_test = np.linspace(0, 1) ax.plot(u_test, model(res, u_test), '--', zorder=-10)
def run(cls, results): direct_exchange, indirect_exchange = results.direct_exchanges, results.indirect_exchanges t_max = len(direct_exchange) money_time_line = np.zeros(t_max) money = {0: 0, 1: 0, 2: 0, -1: 0} interruptions = 0 for t in range(t_max): money_t = cls._test_for_money_state( direct_exchange=direct_exchange[t], indirect_exchange=indirect_exchange[t]) money_time_line[t] = money_t money[money_t] += 1 if t > 0: cond0 = money_t == -1 cond1 = money_time_line[t - 1] != -1 interruptions += cond0 * cond1 # return {"money": money, "interruptions": interruptions} return max([money[0], money[1], money[2]])
def sample_train(data, count=1, test_size=0.4, order=1, random_state=0): res_data = np.zeros((count, 4)) cols = len(data[0]) param_values = {} count_value = np.arange(count) min_value = 0 res_param = None for i in range(count): y = data[:, cols - 1] data_train, data_check, y_train, y_check = train_test_split( data, y, test_size=test_size, random_state=i) print("this is the [%d] learnning:" % i) print("sample_count:%d" % len(data_train)) print("check_count:%d" % len(data_check)) #训练参数与样本准确率 param, accuracy1 = process_data(data_train, 1) #校验数据准确率 accuracy2 = accuracy_data(data_check, param, 1) res_data[i, 0] = accuracy1 res_data[i, 1] = accuracy2 res_data[i, 2] = i res_data[i, 3] = abs(accuracy1 - accuracy2) #print("=====%s"%param) #param = np.c_[param,count_value[i-1]] #param_values[i] = param if i == 0: min_value = res_data[i, 3] res_param = param if res_data[i, 3] < min_value: min_value = res_data[i, 3] res_param = param return res_data, res_param
def run_evo_plot(self): """ Awesome! All agents become chips!""" t_max = 100 culture_length = 5 env = Environment(culture_length=culture_length, t_max=t_max, n_agent=1000, influence_type='linear') all_possible_cultures = list( product([False, True], repeat=culture_length)) all_time_cul = np.zeros((t_max, len(all_possible_cultures))) #TODO: try to understand why #all_time_cul = np.zeros((t_max, len(all_possible_cultures))) # do not work print(len(all_possible_cultures)) print(2**culture_length) # env.plot() for t in tqdm(range(t_max)): env.one_step() for agent in env.agents: all_time_cul[ t, all_possible_cultures.index(tuple(agent.culture))] += 1 plt.figure() plt.plot(all_time_cul)
def getPointMask(p, depth, r): diff = 5 cmask = np.zeros(depth.shape, np.bool) drawC(p, cmask, v=True, r=r) dv = depth[p[0], p[1]] gt, lt = dv + diff, max(1, dv - diff) mask = (depth > lt) * (depth < gt) * cmask return mask
def plot(cls, suffix, data_folder=None, multi=0): if data_folder: parameters, direct_exchange, indirect_exchange = import_data( suffix=suffix, data_folder=data_folder) else: parameters, direct_exchange, indirect_exchange = import_data( suffix=suffix) if multi: nb_list = len(indirect_exchange) t_max = len(indirect_exchange[0]) agents_proportions = np.zeros((t_max, 3)) for i in range(nb_list): for k in range(t_max): for j in range(3): agents_proportions[k, j] = direct_exchange[i][k][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix) else: t_max = len(indirect_exchange) agents_proportions = np.zeros((t_max, 3)) for i in range(t_max): for j in range(3): agents_proportions[i, j] = indirect_exchange[i][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, suffix=suffix, parameters=parameters)
def process_data_file(file): data = loaddata(file, ',') #data = data/100.0 # 获取第3列 y = np.c_[data[:, 9]] # 获取第1、2列 X = data[:, 1:9] #X = X/10.0 #6阶多项式 poly = PolynomialFeatures(1) #标准化数据,保证每个维度的特征数据方差为1,均值为0 data = np.c_[X, y] #X = Normalizer().fit_transform(X) XX = poly.fit_transform(X) #初始化参数为0 initial_theta = np.zeros(XX.shape[1]) #获取图句柄 #fig, axes = plt.subplots(1, 3, sharey=True, figsize=(17, 5)) # 决策边界,咱们分别来看看正则化系数lambda太大太小分别会出现什么情况 # Lambda = 0 : 就是没有正则化,这样的话,就过拟合咯 # Lambda = 1 : 这才是正确的打开方式 # Lambda = 100 : 卧槽,正则化项太激进,导致基本就没拟合出决策边界 lambdas = [1] for i, C in enumerate(lambdas): #300次迭代, 'disp': True res = minimize(costFunctionReg, initial_theta, args=(C, XX, y), jac=gradientReg, options={'maxiter': 2000}) #预测值是否正确 pre_value = predict(res.x, XX) #预测准确率 accuracy = 100.0 * sum(pre_value == y.ravel()) / y.size #画数据分布图 #print ('draw dot >>>>>>>>>>>>>>>>') #plotData(data, 'Microchip Test 1', 'Microchip Test 2', 'y = 1', 'y = 0', axes.flatten()[i], False) #print ('draw line >>>>>>>>>>>>>>>>') #画函数曲线图 #draw_line(poly, X, res.x, accuracy, axes, C, i) print('===========================================') print('lamba:') print(C) print('accuracy:') print(accuracy) print('param:') print(res.x) print('============================================') return res.x
def compute(): pos = np.arange(0, n_positions) a = np.zeros((len(pos), len(pos))) b = np.zeros((len(pos), len(pos)), dtype=list) for x1, x2 in it.product(pos, repeat=2): b[x1, x2] = list() for c in pos: # For each client print("Customer", c) if mode == "fixed_radius": field_of_view = get_field_of_view_with_fixed_radius(c) else: field_of_view = get_field_of_view(c) print("Field of view", field_of_view) for x1, x2 in it.product(pos, repeat=2): see_firm_1 = field_of_view[0] <= x1 <= field_of_view[1] see_firm_2 = field_of_view[0] <= x2 <= field_of_view[1] if cond == "see_both" and see_firm_1 and see_firm_2: a[x1, x2] += 1 b[x1, x2].append(c) if cond == "see_firm_1" and see_firm_1 and not see_firm_2: a[x1, x2] += 1 if cond == "see_firm_2" and not see_firm_1 and see_firm_2: a[x1, x2] += 1 # for i in np.arange(n_positions - 1, -1, -1): # print(i, [j for j in b[i]]) return a
def arc(r0, R, e, n, phi0, phi): e1 = e / np.sqrt(np.sum(e * e)) # normalize en = n / np.sqrt(np.sum(n * n)) # normalize ip = np.argmax(phi > phi0) # find end index e2 = np.cross(en, e1) cp = np.cos(np.radians(phi[:ip])) sp = np.sin(np.radians(phi[:ip])) # r = cp*e1+sp*e2 r = np.zeros((3, ip)) r[0, :] = r0[0] + R * (cp * e1[0] + sp * e2[0]) r[1, :] = r0[1] + R * (cp * e1[1] + sp * e2[1]) r[2, :] = r0[2] + R * (cp * e1[2] + sp * e2[2]) return r
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()
def plot(cls, session_suffix, eco_idx): data_importer = DataImporter(session_suffix=session_suffix) parameters = data_importer.get_parameters(eco_idx) # direct_exchange = data_importer.get_exchanges(eco_idx, "direct") indirect_exchange = data_importer.get_exchanges(eco_idx, "indirect") t_max = len(indirect_exchange) agents_proportions = np.zeros((t_max, 3)) for i in range(t_max): for j in range(3): agents_proportions[i, j] = indirect_exchange[i][j] cls.draw(agents_proportions=agents_proportions, t_max=t_max, eco_idx=eco_idx, parameters=parameters)
def compute(): fov = np.arange(0, 1, 1 / n_positions) pos = np.arange(0, n_positions) a = np.zeros((len(fov), len(pos))) for f_i, f in enumerate(fov): for c in pos: # For each client if mode == "fixed_radius": field_of_view = get_field_of_view_with_fixed_radius(c, f) else: field_of_view = get_field_of_view(c, f) for x in pos: # For each position of the firm a[f_i, x] += int(field_of_view[0] <= x <= field_of_view[1]) return a
def process_data(data, order=2, count=2000): #6阶多项式 poly = PolynomialFeatures(order) #标准化数据,保证每个维度的特征数据方差为1,均值为0 #X = Normalizer().fit_transform(X) cols = len(data[0]) #获取特征向量 X = data[:, 0:cols - 1] y = np.c_[data[:, cols - 1]] XX = poly.fit_transform(X) #初始化参数为0 initial_theta = np.zeros(XX.shape[1]) #获取图句柄 #fig, axes = plt.subplots(1, 3, sharey=True, figsize=(17, 5)) # 决策边界,咱们分别来看看正则化系数lambda太大太小分别会出现什么情况 # Lambda = 0 : 就是没有正则化,这样的话,就过拟合咯 # Lambda = 1 : 这才是正确的打开方式 # Lambda = 100 : 卧槽,正则化项太激进,导致基本就没拟合出决策边界 lambdas = [1] for i, C in enumerate(lambdas): #300次迭代, 'disp': True res = minimize(costFunctionReg, initial_theta, args=(C, XX, y), jac=gradientReg, options={'maxiter': 2000}) pre_value = predict(res.x, XX) accuracy = 100.0 * sum(pre_value == y.ravel()) / y.size print('===========================================') print('lamba:') print(C) print('accuracy:') print(accuracy) print('param:') print(res.x) print('============================================') return res.x, accuracy
def get_most_robust_convictions(self, n=1): # np.argsort() returns the indices that would sort the array # [::-1] reverse the sorting from increasing to decreasing order # [:n] selects the n first elements unique_convictions_values = np.unique(self.convictions) if len(unique_convictions_values) == len(self.convictions): return np.argsort(np.absolute(self.convictions))[::-1][:n] else: # Class in decreasing order the unique different values of convictions sorted_unique_values = sorted(unique_convictions_values, reverse=True) to_return = np.zeros(len(self.convictions), dtype=int) i = 0 for value in sorted_unique_values: list_of_idx = np.where(self.convictions == value)[0] to_return[i:i + len(list_of_idx)] = np.random.permutation( list_of_idx) i += len(list_of_idx) return np.asarray(to_return)
def __new__(cls, convictions): self = np.array(np.zeros(len(convictions), dtype=int)).view(cls) return self
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)
femm.mi_smartmesh(0) # femm.mi_saveas(f'temp-{id_solver}.fem') femm.mi_analyze(1) # None for inherited. 1 for a minimized window, print(f'{index:02d}', project_file_name[:-4] + f'-{index:03d}.fem | Solving time: {time() - tic:.1f} s ', end='') femm.mi_loadsolution() # femm.mo_smooth('off') # flux smoothing algorithm is off if bool_initialized == False: bool_initialized = True # Record the initial mesh elements if the first time through the loop nn = int(femm.mo_numelements()) M = np.zeros([ns, 22]) # 9 columns of performance data matrix z = np.zeros( [nn, 1], dtype=np.complex64) # Location of the centroid of each element a = np.zeros([nn, 1]) # Area of each element g = np.zeros([nn, 1]) # Block label of each element for m in range( nn): # start from 0 for indexing but from 1 for counting counting_element = m + 1 elm = femm.mo_getelement(counting_element) # z is a vector of complex numbers that represents the location of the centroid of each element. z[m] = elm[4 - 1] + 1j * elm[5 - 1] # element area in the length units used to draw the geometry a[m] = elm[6 - 1] # group number associated with the element
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 plot_customer_firm_choices(self, period=50): # Data positions = self.results["positions"][-period:] prices = self.results["prices"][-period:] n_firms = len(self.results["positions"][0]) customer_firm_choices = self.results["customer_firm_choices"][-period:] t_max, n_positions = customer_firm_choices.shape # Create fig and axes fig = plt.figure(figsize=(t_max, n_positions)) gs = gridspec.GridSpec(24, 20) ax = fig.add_subplot(gs[:20, :20]) ax2 = fig.add_subplot(gs[-1, 8:12]) # Prepare normalization for 'imshow' mapping = dict([(x, y) for x, y in zip(np.arange(-1, n_firms), np.linspace(0, 1, n_firms + 1))]) f_mapping = lambda x: mapping[x] # Function adapted for numpy array v_func = np.vectorize(f_mapping) # Format customer choices (reordering + normalization) formatted_customer_firm_choices = v_func(customer_firm_choices.T[::-1]) # Colors for different firms firm_colors = cm.ScalarMappable(norm=None, cmap="gist_rainbow").to_rgba( np.linspace(0, 1, n_firms)) # Prepare customized colormap colors = np.zeros((n_firms + 1, 4)) colors[0] = 1, 1, 1, 1 # White colors[1:] = firm_colors cmap_name = "manual_colormap" n_bins = n_firms + 1 manual_cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins) # Plot customer choices ax.imshow(formatted_customer_firm_choices, interpolation='nearest', origin="lower", norm=NoNorm(), alpha=0.5, cmap=manual_cm) # Offsets for positions plot and prices plot offsets = np.linspace(-0.25, 0.25, n_firms) # Plot positions for i in range(n_firms): ax.plot(np.arange(t_max) + offsets[i], n_positions - positions[:, i], "o", color=firm_colors[i], markersize=10) # Plot prices for t in range(t_max): for i in range(n_firms): ax.text(t + offsets[i] - 0.1, n_positions - positions[t, i] + 0.2, prices[t, i]) # Customize axes ax.set_xlim(-0.5, t_max - 0.5) ax.set_ylim(-0.5, n_positions - 0.5) # Add grid (requires to customize axes) ax.set_yticks(np.arange(0.5, n_positions - 0.5, 1), minor=True) ax.set_xticks(np.arange(0.5, t_max - 0.5, 1), minor=True) ax.grid(which='minor', axis='y', linewidth=2, linestyle=':', color='0.75') ax.grid(which='minor', axis='x', linewidth=2, linestyle='-', color='0.25') # After positioning grid, replace ticks for placing labels ax.set_xticks(range(t_max)) ax.set_yticks(range(n_positions)) # Top is position 1. ax.set_yticklabels(np.arange(1, n_positions + 1)[::-1]) # Set axes labels ax.set_xlabel('t', fontsize=14) ax.set_ylabel('Position', fontsize=14) # Remove ticks ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') # Legend possibilities = v_func(np.arange(-1, n_firms)) ax2.imshow(np.atleast_2d(possibilities), interpolation='nearest', origin="lower", norm=NoNorm(), cmap=manual_cm) # Customize ticks ax2.xaxis.set_ticks_position('none') ax2.yaxis.set_ticks_position('none') ax2.set_yticks([]) lab = [str(i) for i in np.arange(-1, n_firms)] ax2.set_xticks(np.arange(n_firms + 1)) ax2.set_xticklabels(lab) plt.savefig(self.format_fig_name("customers_choices")) 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 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()