mcmc.py 6.46 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
import optparse
import yaml
import time
import pickle as pkl
import pandas as pd
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
from tensorflow_probability import bijectors as tfb
import matplotlib.pyplot as plt
11
from tensorflow_probability.python.util import SeedStream
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

from covid.rdata import load_population, load_age_mixing, load_mobility_matrix
from covid.model import CovidUKODE, covid19uk_logp
from covid.util import *


def plotting(dates, sim):
    print("Initial R0:", simulator.eval_R0(param))
    print("Doubling time:", doubling_time(dates, sim.numpy(), '2020-02-27','2020-03-13'))

    fig = plt.figure()
    removals = tf.reduce_sum(sim[:, 3, :], axis=1)
    infected = tf.reduce_sum(sim[:, 1:3, :], axis=[1,2])
    exposed = tf.reduce_sum(sim[:, 1, :], axis=1)
    date = np.squeeze(np.where(dates == np.datetime64('2020-03-13'))[0])
    print("Daily incidence 2020-03-13:", exposed[date]-exposed[date-1])

    plt.plot(dates, removals*0.10, '-', label='10% reporting')
    plt.plot(dates, infected, '-', color='red', label='Total infected')
    plt.plot(dates, removals, '-', color='gray', label='Total recovered/detected/died')

    plt.scatter(np.datetime64('2020-03-13'), 600, label='gov.uk cases 13th March 2020')
    plt.legend()
    plt.grid(True)
    fig.autofmt_xdate()
    plt.show()


40
41
def random_walk_mvnorm_fn(covariance, name=None):
    """Returns callable that adds Multivariate Normal noise to the input"""
42
    covariance = covariance + tf.eye(covariance.shape[0], dtype=tf.float64) * 1.e-9
43
44

    rv = tfp.distributions.MultivariateNormalTriL(loc=tf.zeros(covariance.shape[0], dtype=tf.float64),
45
46
47
                                                  scale_tril=tf.linalg.cholesky(
                                                      tf.convert_to_tensor(covariance,
                                                                           dtype=tf.float64)))
48
49
50

    def _fn(state_parts, seed):
        with tf.name_scope(name or 'random_walk_mvnorm_fn'):
51
52
53
54
55
            new_state_parts = rv.sample() + state_parts
            return new_state_parts

    return _fn

56
57


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
if __name__ == '__main__':

    parser = optparse.OptionParser()
    parser.add_option("--config", "-c", dest="config",
                      help="configuration file")
    options, args = parser.parse_args()
    with open(options.config, 'r') as ymlfile:
        config = yaml.load(ymlfile)

    K_tt, age_groups = load_age_mixing(config['data']['age_mixing_matrix_term'])
    K_hh, _ = load_age_mixing(config['data']['age_mixing_matrix_hol'])

    T, la_names = load_mobility_matrix(config['data']['mobility_matrix'])
    np.fill_diagonal(T, 0.)

    N, n_names = load_population(config['data']['population_size'])

    param = sanitise_parameter(config['parameter'])
    settings = sanitise_settings(config['settings'])

    case_reports = pd.read_csv(config['data']['reported_cases'])
    case_reports['DateVal'] = pd.to_datetime(case_reports['DateVal'])
    date_range = [case_reports['DateVal'].min(), case_reports['DateVal'].max()]
    y = case_reports['CumCases'].to_numpy()
    y_incr = np.round((y[1:] - y[:-1]) * 0.8)

    simulator = CovidUKODE(K_tt, K_hh, T, N, date_range[0]-np.timedelta64(1,'D'),
Chris Jewell's avatar
Chris Jewell committed
85
                           date_range[1], settings['holiday'], settings['bg_max_time'], int(settings['time_step']))
86
87
88
89

    seeding = seed_areas(N, n_names)  # Seed 40-44 age group, 30 seeds by popn size
    state_init = simulator.create_initial_state(init_matrix=seeding)

90
    #@tf.function
91
    def logp(par):
92
        p = param
93
94
        p['epsilon'] = par[0]
        p['beta1'] = par[1]
95
        p['gamma'] = par[2]
96
97
98
        epsilon_logp = tfd.Gamma(concentration=tf.constant(1., tf.float64), rate=tf.constant(1., tf.float64)).log_prob(p['epsilon'])
        beta_logp = tfd.Gamma(concentration=tf.constant(1., tf.float64), rate=tf.constant(1., tf.float64)).log_prob(p['beta1'])
        gamma_logp = tfd.Gamma(concentration=tf.constant(100., tf.float64), rate=tf.constant(400., tf.float64)).log_prob(p['gamma'])
99
100
        t, sim, solve = simulator.simulate(p, state_init)
        y_logp = covid19uk_logp(y_incr, sim, 0.1)
101
        logp = epsilon_logp + beta_logp + gamma_logp + tf.reduce_sum(y_logp)
Chris Jewell's avatar
Chris Jewell committed
102
        return logp
103

Chris Jewell's avatar
Chris Jewell committed
104
105
106
107
108
109
110
    def trace_fn(_, pkr):
      return (
          pkr.inner_results.log_accept_ratio,
          pkr.inner_results.accepted_results.target_log_prob,
          pkr.inner_results.accepted_results.step_size)


111
    unconstraining_bijector = [tfb.Exp()]
112
    initial_mcmc_state = np.array([0.001,  0.036, 0.25], dtype=np.float64)
113
    print("Initial log likelihood:", logp(initial_mcmc_state))
114

115
    @tf.function(experimental_compile=True)
116
    def sample(n_samples, init_state, scale):
117
        return tfp.mcmc.sample_chain(
Chris Jewell's avatar
Chris Jewell committed
118
119
            num_results=n_samples,
            num_burnin_steps=0,
120
121
122
            current_state=init_state,
            kernel=tfp.mcmc.TransformedTransitionKernel(
                    inner_kernel=tfp.mcmc.RandomWalkMetropolis(
123
                        target_log_prob_fn=logp,
124
125
                        new_state_fn=random_walk_mvnorm_fn(scale)
                    ),
126
                    bijector=unconstraining_bijector),
127
            trace_fn=lambda _, pkr: pkr.inner_results.is_accepted)
Chris Jewell's avatar
Chris Jewell committed
128
129

    with tf.device("/CPU:0"):
130
        cov = np.diag([0.00001, 0.00001, 0.00001])
Chris Jewell's avatar
Chris Jewell committed
131
        start = time.perf_counter()
132
        joint_posterior, results = sample(50, init_state=initial_mcmc_state, scale=cov)
133
        for i in range(200):
134
            cov = tfp.stats.covariance(tf.math.log(joint_posterior)) * 2.38**2 / joint_posterior.shape[1]
135
            print(cov.numpy())
136
            posterior_new, results = sample(50, joint_posterior[-1, :], cov)
137
            joint_posterior = tf.concat([joint_posterior, posterior_new], axis=0)
138
139
        #posterior_new, results = sample(2000, init_state=joint_posterior[-1, :], scale=cov)
        #joint_posterior = tf.concat([joint_posterior, posterior_new], axis=0)
Chris Jewell's avatar
Chris Jewell committed
140
141
        end = time.perf_counter()
        print(f"Simulation complete in {end-start} seconds")
142
        print("Acceptance: ", np.mean(results.numpy()))
143
        print(tfp.stats.covariance(tf.math.log(joint_posterior)))
Chris Jewell's avatar
Chris Jewell committed
144

145
146
147
    fig, ax = plt.subplots(1, 3)
    ax[0].plot(joint_posterior[:, 0])
    ax[1].plot(joint_posterior[:, 1])
148
    ax[2].plot(joint_posterior[:, 2])
149
    plt.show()
150
    print(f"Posterior mean: {np.mean(joint_posterior, axis=0)}")
151

Chris Jewell's avatar
Chris Jewell committed
152
    with open('pi_beta_2020-03-15.pkl', 'wb') as f:
153
        pkl.dump(joint_posterior, f)
154
155
156

    #dates = settings['start'] + t.numpy().astype(np.timedelta64)
    #plotting(dates, sim)