예제 #1
0
 def __computeIntLambda(self, trial, custom_eta=None):
     """
     Compute integral from 0 to T of (0.5 * Qlam * u^2) dt 
     for a given trial.
     """
     hf = HelperFunc()
     if custom_eta is None:
         eta = trial['info']['eta']
     else:
         eta = custom_eta
     u_, Qlam = trial['u'], trial['info']['Qlam']
     t, u = hf.step_sps_values_over_time(u_, summed=False)
     if u:
         f_of_t = t, 0.5 * np.dot(Qlam, np.square(np.array(u)).T)
     else:
         f_of_t = t, 0
     return self.__integrateF(f_of_t, eta)
예제 #2
0
    def _computeIntH(self, trial, custom_eta=None):
        """
        Compute integral from 0 to T of |H|_1 dt for a given trial.
        """
        hf = HelperFunc()
        if custom_eta is None:
            eta = trial['info']['eta']
        else:
            eta = custom_eta
        H_ = trial['H']
        t, H = hf.step_sps_values_over_time(H_, summed=False)

        if H:
            f_of_t = t, np.dot(np.ones(trial['info']['N']), np.array(H).T)
        else:
            f_of_t = t, 0

        return self.__integrateF(f_of_t, eta)
예제 #3
0
 def computeIntX(self, trial, custom_eta=None, weight_by_Qx=True):
     """
     Compute the integral from 0 to T of (Qx * X) dt for a given trial.
     """
     hf = HelperFunc()
     if custom_eta is None:
         eta = trial['info']['eta']
     else:
         eta = custom_eta
     X_, Qx = trial['X'], trial['info']['Qx']
     t, X = hf.step_sps_values_over_time(X_, summed=False)
     if X:
         if weight_by_Qx:
             f_of_t = t, np.dot(Qx, np.array(X).T)
         else:
             f_of_t = t, np.dot(np.ones(Qx.shape), np.array(X).T)
     else:
         f_of_t = t, 0
     return self.__integrateF(f_of_t, eta)
예제 #4
0
    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
예제 #5
0
    def compare_infections(self, size_tup=(8, 6), save=True):
        """
        Compare infections along Qx axis (assuming Qlambda = const = 1.0).
        """
        d = self.multi_summary.get('infections_and_interventions', None)
        Qs = self.multi_summary.get('Qs', None)

        if d is None or Qs is None:
            raise ValueError('Missing data.')

        keys = np.array(list(Qs.keys()))
        n_exps = len(keys)

        # assumes data had same methods tested
        infections_axis = {name: np.zeros(n_exps) for name in self.policy_list}
        infections_axis_std = {
            name: np.zeros(n_exps)
            for name in self.policy_list
        }
        interventions_axis = {
            name: np.zeros(n_exps)
            for name in self.policy_list
        }
        interventions_axis_std = {
            name: np.zeros(n_exps)
            for name in self.policy_list
        }

        # Build X-axis
        Qx_axis = np.array([Qs[key] for key in keys])
        # Sort by value
        sorted_args = np.argsort(Qx_axis)
        Qx_axis = Qx_axis[sorted_args]
        keys = keys[sorted_args]

        # Build Y-axis
        for i, name in enumerate(self.policy_list):
            for j, key in enumerate(keys):
                # d[key] = ((intX_m, intX_s), (N_m, N_s), (intH_m, intH_s), (Y_m, Y_s))
                infections_axis[name][j] = d[key][0][0][i]
                infections_axis_std[name][j] = d[key][0][1][i] / np.sqrt(
                    self.n_trials)  # transfrom stddev into std error
                interventions_axis[name][j] = d[key][1][0][i]
                interventions_axis_std[name][j] = d[key][1][1][i] / np.sqrt(
                    self.n_trials)  # transfrom stddev into std error

        # Set up figure.
        fig, ax = plt.subplots(1, 1, figsize=(12, 8), facecolor='white')
        plt.cla()

        hf = HelperFunc()

        legend = []
        max_infected = 0
        for ind, name in enumerate(self.policy_list):
            legend.append(name)

            # linear axis
            ax.plot(Qx_axis,
                    infections_axis[name],
                    color=self.colors[ind],
                    linestyle=self.linestyles[ind])
            ax.fill_between(
                Qx_axis,
                infections_axis[name] - interventions_axis_std[name],
                infections_axis[name] + interventions_axis_std[name],
                alpha=0.3,
                edgecolor=self.colors[ind],
                facecolor=self.colors[ind],
                linewidth=0)

            # ax.errorbar(Qx_axis, infections_axis[name], yerr=interventions_axis_std[name])

            if max(infections_axis[name]) > max_infected:
                max_infected = max(infections_axis[name])

        ax.set_xlim([0.7, max(Qx_axis)])
        ax.set_xlabel(r'$Q_x$')
        ax.set_ylim([0, 1.3 * max_infected])
        ax.set_ylabel(
            r'Infection coverage $\int_{t_0}^{t_f} \mathbf{X}(t) dt$')
        ax.legend(legend)

        # ax.set_xscale("log", nonposx='clip')

        if save:
            dpi = 300
            # plt.tight_layout()
            fig = plt.gcf()  # get current figure
            fig.set_size_inches(size_tup)  # width, height
            plt.savefig(os.path.join(self.save_dir,
                                     'infections_fair_comparison.png'),
                        frameon=False,
                        format='png',
                        dpi=dpi)
            plt.close()
        else:
            plt.show()
예제 #6
0
    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()
예제 #7
0
    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))
예제 #8
0
from analysis import Evaluation
from stochastic_processes import StochasticProcess, CountingProcess

from helpers import HelperFunc


'''Construct network from input'''
df = pd.read_csv("data/contiguous-usa.txt", sep=" ", header=None)
df = df - 1
df = df.drop(columns=[2])
df_0, df_1 = df[0].values, df[1].values
N, M = max(np.max(df_0), np.max(df_1)) + 1, len(df_0)

# load X, u
print('load X, u...')
hf = HelperFunc()
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: