def summarize_interventions_and_intensities(self): """ Return total number of interventions & peak and average treatment intensities for every heuristic. """ hf = HelperFunc() # Intensities max_intensities = np.zeros((len(self.data), len(self.data[0])), dtype=object) for i, heuristic in enumerate(tqdm(self.data)): for j, trial in enumerate(heuristic): all_arrivals = hf.all_arrivals(trial['u']) max_intensities[i, j] = np.zeros(len(all_arrivals)) for k, t in enumerate(all_arrivals): max_intensities[i, j][k] = np.max( hf.sps_values(trial['u'], t, summed=False)) max_per_trial = [[np.max(trial) for trial in heuristic] for heuristic in tqdm(max_intensities)] max_per_heuristic = [np.max(heuristic) for heuristic in max_per_trial] print(max_per_trial) print(max_per_heuristic) # Treatments # treatments_by_heuristic = [[hf.sps_values(trial['Nc'], trial['info']['ttotal'], summed=True) # for trial in heuristic] for heuristic in self.data] # means_treatment, stddevs_treatment = \ # [np.mean(treatments) for treatments in treatments_by_heuristic], \ # [np.std(treatments) for treatments in treatments_by_heuristic] return 0 # TODO Change back and delete this
def simulation_plot(self, process, figsize=(8, 6), granularity=0.1, filename='simulation_summary', draw_box=False, save=False): """ Plot a summary of the simulation. Parameters ---------- process : str Process to plot (`X`, `H`, `Y`, `W`, `Nc`, `u`) figsize : tuple, optional Figure size granularity : float, optional Time (x-axis) granularity of the plot filename : str, optional Filename to save the plot save : bool, optional If True, the plot is saved to `filename` draw_box : bool, optional If True, draw a text box with simulation parameters """ print(f"Building simulation figure for process {process:s}...") fig, ax = plt.subplots(1, 1, figsize=figsize) hf = HelperFunc() for i, heuristic in enumerate(self.data): # Number of trials n_trials = len(heuristic) # Simulation end time ttotal = heuristic[0]['info']['ttotal'] # Linearly spaced array of time tspace = np.arange(0.0, ttotal, granularity) # Extract the values of the stochastic processes at all times # for each trial values = np.zeros((n_trials, len(tspace))) for j, trial in enumerate(tqdm_notebook(heuristic)): for k, t in enumerate(tspace): values[j, k] = hf.sps_values(trial[process], t, summed=True) # Compute mean and std over trials mean_X_t = np.mean(values, axis=0) stddev_X_t = np.std(values, axis=0) # Plot the mean +/- std ax.plot(tspace, mean_X_t, color=self.colors[i], linestyle=self.linestyles[i]) ax.fill_between(tspace, mean_X_t - stddev_X_t, mean_X_t + stddev_X_t, alpha=0.3, edgecolor=self.colors[i], facecolor=self.colors[i], linewidth=0) ax.set_xlim([0, ttotal]) ax.set_xlabel("Elapsed time") # ax.set_ylim([0, heuristic[0]['info']['N']]) ax.set_ylim(bottom=0) if process == 'X': ax.set_ylabel("Number of infected nodes") elif process == 'H': ax.set_ylabel("Number of treated nodes") else: ax.set_ylabel("Number of nodes") # Text box if draw_box: s = self.__getTextBoxString() _, upper = ax.get_ylim() plt.text(0.0, upper, s, size=12, va="baseline", ha="left", multialignment="left", bbox=dict(fc="none")) # Legend legend = [] for policy in self.descr: legend += [policy] ax.legend(legend) plt.draw() if save: fig_filename = os.path.join(self.dirname, filename + '.pdf') plt.savefig(fig_filename, format='pdf', frameon=False, dpi=300) plt.close() else: plt.show()
def infections_and_interventions_complete(self, size_tup=(15, 10), save=False): """ Summarizes simulations in 3 plots - Infection coverage (Int X(t) dt) - Total discrete interventions (Sum N(T)) - Infection coverage (Int X(t) dt) - Treatment coverage (Int H(t) dt) - Infection events (Sum Y(T)) - Total discrete interventions (Sum N(T)) """ # Compute statistics for every heuristic hf = HelperFunc() intX_by_heuristic = [[ self.computeIntX(trial, custom_eta=0.0, weight_by_Qx=False) for trial in heuristic ] for heuristic in tqdm_notebook(self.data)] intX_m = np.array([np.mean(h) for h in intX_by_heuristic]) intX_s = np.array([np.std(h) for h in intX_by_heuristic]) intH_by_heuristic = [[ self._computeIntH(trial, custom_eta=0.0) for trial in heuristic ] for heuristic in tqdm_notebook(self.data)] intH_m = np.array([np.mean(h) for h in intH_by_heuristic]) intH_s = np.array([np.std(h) for h in intH_by_heuristic]) Y_by_heuristic = [[ hf.sps_values(trial['Y'], trial['info']['ttotal'], summed=True) for trial in heuristic ] for heuristic in tqdm_notebook(self.data)] Y_m = np.array([np.mean(h) for h in Y_by_heuristic]) Y_s = np.array([np.std(h) for h in Y_by_heuristic]) N_by_heuristic = [[ hf.sps_values(trial['Nc'], trial['info']['ttotal'], summed=True) for trial in heuristic ] for heuristic in tqdm_notebook(self.data)] N_m = np.array([np.mean(h) for h in N_by_heuristic]) N_s = np.array([np.std(h) for h in N_by_heuristic]) x = np.arange(len(intX_m)) n = 50 # trials per simulation # Plotting functionality plt.rc('text', usetex=True) plt.rc('font', family='serif') fig = plt.figure(figsize=(12, 8), facecolor='white') # 1 - Infection coverage (Int X(t) dt) - Total discrete interventions (Sum N(T)) ax = fig.add_subplot(2, 1, 1, frameon=False) width = 0.2 ax.bar(x, intX_m, yerr=intX_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc') ax.set_xticks(x + width / 2) ax.set_xlabel(r'Policies') ax.set_xticklabels(self.descr) ax.set_ylabel( r'Infection coverage $\int_{t_0}^{t_f} \mathbf{X}(t) dt$') ax2 = ax.twinx() ax2.patch.set_visible(False) ax2.bar(x + width, N_m, yerr=N_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc', alpha=0.5) ax2.set_ylabel( r'Interventions $\sum_{i=1}^{|nodes|} \mathbf{N}_i(t_f)$') plt.title(r"Infection coverage and discrete interventions") # 2 - Infection coverage (Int X(t) dt) - Treatment coverage (Int H(t) dt) ax = fig.add_subplot(2, 2, 3, frameon=False) width = 0.2 ax.bar(x, intX_m, yerr=intX_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc') ax.set_xticks(x + width / 2) ax.set_xlabel(r'Policies') ax.set_xticklabels([''] * len(self.descr)) ax.set_ylabel( r'Infection coverage $\int_{t_0}^{t_f} \mathbf{X}(t) dt$') ax2 = ax.twinx() ax2.patch.set_visible(False) ax2.bar(x + width, intH_m, yerr=intH_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc', alpha=0.5) ax2.set_ylabel( r'Treatment coverage $\int_{t_0}^{t_f} \mathbf{H}(t) dt$') plt.title(r"Infection coverage and treatment coverage") # 3 - Infection events (Sum Y(T)) - Total discrete interventions (Sum N(T)) ax = fig.add_subplot(2, 2, 4, frameon=False) width = 0.2 ax.bar(x, intX_m, yerr=intX_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc') ax.set_xticks(x + width / 2) ax.set_xlabel(r'Policies') ax.set_xticklabels([''] * len(self.descr)) ax.set_ylabel(r'Infections $\sum_{i=1}^{|nodes|} \mathbf{Y}_i(t_f)$') ax2 = ax.twinx() ax2.patch.set_visible(False) ax2.bar(x + width, N_m, yerr=N_s / np.sqrt(n), width=width, align='center', color='rgbkymcgbkymc', alpha=0.5) ax2.set_ylabel( r'Interventions $\sum_{i=1}^{|nodes|} \mathbf{N}_i(t_f)$') plt.title(r"Infection events and discrete interventions") plt.tight_layout() if save: fig_filename = os.path.join( self.dirname, "infections_and_interventions_complete" + '.pdf') plt.savefig(fig_filename, format='pdf', frameon=False, dpi=300) plt.close() else: plt.show() return ((intX_m, intX_s), (N_m, N_s), (intH_m, intH_s), (Y_m, Y_s))
filename = 'results_comparison_OPT_T_MN_complete_8_50__Q_1_400_.pkl' data = joblib.load('temp_pickles/' + filename) print('done.') times = np.arange(1.0, 4.0, 0.1).tolist() times2 = np.arange(1.001, 4.001, 0.1).tolist() times = times + times + times2 times.sort() trial_no = 1 for t in times: u_t = hf.sps_values(data[0][trial_no]['u'], t, summed=False) X_t = hf.sps_values(data[0][trial_no]['X'], t, summed=False) G = nx.from_pandas_edgelist(df.astype('i'), 0, 1, create_using=nx.Graph()) # And a data frame with characteristics for your nodes # X = [0 if i % 4 == 0 else 1 for i in range(N)] # u = [i for i in range(N)] X = list(X_t) u = list(u_t) # Infection tags carac = pd.DataFrame({'ID': G.nodes(), 'myvalue': X}) carac['myvalue'] = pd.Categorical(carac['myvalue']) pos = nx.spring_layout(G, k=0.04)