Beispiel #1
0
    def __init__(self,
                 model,
                 mu_0=0.,
                 lmbda_0=1.,
                 alpha_0=1.,
                 beta_0=1.,
                 delay_0=0.0,
                 normal_mu=0.1,
                 normal_sig=0.3):
        self.model = model
        self.K = model.K
        self.dt_max = model.dt_max

        self.mu_0 = mu_0
        self.lmbda_0 = lmbda_0
        self.alpha_0 = alpha_0
        self.beta_0 = beta_0

        self.delay_0 = delay_0
        self.normal_sig = normal_sig
        self.normal_mu = normal_mu
        self.delay = self.normal_mu * np.ones((self.K, self.K), dtype='double')

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(self.mu_0 * np.ones((self.K, self.K)),
                       self.lmbda_0 * np.ones((self.K, self.K)),
                       self.alpha_0 * np.ones((self.K, self.K)),
                       self.beta_0 * np.ones((self.K, self.K)))
Beispiel #2
0
    def resample(self, data=[]):
        """
        Resample the
        :param data: a TxKxKxB array of parents. T time bins, K processes,
                     K parent processes, and B bases for each parent process.
        """
        mu_0, lmbda_0, alpha_0, beta_0 = self.mu_0, self.lmbda_0, self.alpha_0, self.beta_0
        assert data is None or isinstance(data, list)

        # 0: count, # 1: Sum of scaled dt, #2: Sum of sq scaled dt
        ss = np.zeros((3, self.K, self.K))
        for d in data:
            ss += d.compute_imp_suff_stats()

        n = ss[0]
        xbar = np.nan_to_num(ss[1] / n)
        xvar = ss[2]

        alpha_post = alpha_0 + n / 2.
        # beta_post = beta_0 + 0.5 * xvar
        # beta_post += 0.5 * lmbda_0 * n / (lmbda_0 + n) * (xbar-mu_0)**2
        beta_post = beta_0 + 0.5 * xvar + 0.5 * lmbda_0 * n * (xbar-mu_0)**2 / (lmbda_0+n)

        lmbda_post = lmbda_0 + n
        mu_post = (lmbda_0 * mu_0 + n * xbar) / (lmbda_0 + n)

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(mu_post, lmbda_post, alpha_post, beta_post)

        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()
Beispiel #3
0
def test_sample_nig():
    mu_0 = 0.0
    lmbda_0 = 10.
    alpha_0 = 10.
    beta_0 = 10.

    # Directly sample nig and lookg at marginals
    from pyhawkes.utils.utils import sample_nig
    mu_samples = \
        np.array([sample_nig(mu_0, lmbda_0, alpha_0, beta_0)[0]
                  for _ in range(10000)])

    # Plot the histogram of impulse means
    plt.figure()
    p_mu = t(df=2*alpha_0,
             loc=mu_0,
             scale=np.sqrt(beta_0/(alpha_0*lmbda_0)))

    _, bins, _ = plt.hist(mu_samples, bins=50, alpha=0.5, normed=True)
    bincenters = 0.5*(bins[1:]+bins[:-1])
    plt.plot(bincenters, p_mu.pdf(bincenters), 'r--', linewidth=1)
    plt.xlabel('mu')
    plt.ylabel('p(mu)')

    plt.figure()
    probplot(mu_samples, dist=p_mu, plot=plt.gca())

    plt.show()
Beispiel #4
0
    def resample(self, data=[]):
        """
        Resample the
        :param data: a TxKxKxB array of parents. T time bins, K processes,
                     K parent processes, and B bases for each parent process.
        """
        mu_0, lmbda_0, alpha_0, beta_0 = self.mu_0, self.lmbda_0, self.alpha_0, self.beta_0
        assert data is None or isinstance(data, list)

        # 0: count, # 1: Sum of scaled dt, #2: Sum of sq scaled dt
        ss = np.zeros((3, self.K, self.K))
        for d in data:
            ss += d.compute_imp_suff_stats()

        n = ss[0]
        xbar = np.nan_to_num(ss[1] / n)
        xvar = ss[2]

        alpha_post = alpha_0 + n / 2.
        # beta_post = beta_0 + 0.5 * xvar
        # beta_post += 0.5 * lmbda_0 * n / (lmbda_0 + n) * (xbar-mu_0)**2
        beta_post = beta_0 + 0.5 * xvar + 0.5 * lmbda_0 * n * (
            xbar - mu_0)**2 / (lmbda_0 + n)

        lmbda_post = lmbda_0 + n
        mu_post = (lmbda_0 * mu_0 + n * xbar) / (lmbda_0 + n)

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(mu_post, lmbda_post, alpha_post, beta_post)

        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()
Beispiel #5
0
def test_sample_nig():
    mu_0 = 0.0
    lmbda_0 = 10.0
    alpha_0 = 10.0
    beta_0 = 10.0

    # Directly sample nig and lookg at marginals
    from pyhawkes.utils.utils import sample_nig

    mu_samples = np.array([sample_nig(mu_0, lmbda_0, alpha_0, beta_0)[0] for _ in xrange(10000)])

    # Plot the histogram of impulse means
    plt.figure()
    p_mu = t(df=2 * alpha_0, loc=mu_0, scale=np.sqrt(beta_0 / (alpha_0 * lmbda_0)))

    _, bins, _ = plt.hist(mu_samples, bins=50, alpha=0.5, normed=True)
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    plt.plot(bincenters, p_mu.pdf(bincenters), "r--", linewidth=1)
    plt.xlabel("mu")
    plt.ylabel("p(mu)")

    plt.figure()
    probplot(mu_samples, dist=p_mu, plot=plt.gca())

    plt.show()
Beispiel #6
0
    def __init__(self,
                 model,
                 mu_0=0.,
                 lmbda_0=1.,
                 alpha_0=1.,
                 beta_0=1.,
                 support=None):
        self.model = model
        self.K = model.K
        self.dt_max = model.dt_max

        if support is None:
            self.support = (0.05, 0.95)
        else:
            assert len(support) == 2 and support[0] >= 0 and support[1] <= 1
            self.support = (float(support[0]), float(support[1]))
        self.support_width = self.support[1] - self.support[0]
        assert self.support_width > 0

        self.mu_0 = mu_0
        self.lmbda_0 = lmbda_0
        self.alpha_0 = alpha_0
        self.beta_0 = beta_0

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(self.mu_0 * np.ones((self.K, self.K)),
                       self.lmbda_0 * np.ones((self.K, self.K)),
                       self.alpha_0 * np.ones((self.K, self.K)),
                       self.beta_0 * np.ones((self.K, self.K)))
Beispiel #7
0
    def __init__(self, model, mu_0=0., lmbda_0=1., alpha_0=1., beta_0=1.):
        self.model = model
        self.K = model.K
        self.dt_max = model.dt_max

        self.mu_0 = mu_0
        self.lmbda_0 = lmbda_0
        self.alpha_0 = alpha_0
        self.beta_0 = beta_0

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(self.mu_0 * np.ones((self.K, self.K)),
                       self.lmbda_0 * np.ones((self.K, self.K)),
                       self.alpha_0 * np.ones((self.K, self.K)),
                       self.beta_0 * np.ones((self.K, self.K)))
Beispiel #8
0
    def __init__(self, model, mu_0=0., lmbda_0=1., alpha_0=1., beta_0=1.):
        self.model = model
        self.K = model.K
        self.dt_max = model.dt_max

        self.mu_0 = mu_0
        self.lmbda_0 = lmbda_0
        self.alpha_0 = alpha_0
        self.beta_0 = beta_0

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(self.mu_0 * np.ones((self.K, self.K)),
                       self.lmbda_0 * np.ones((self.K, self.K)),
                       self.alpha_0 * np.ones((self.K, self.K)),
                       self.beta_0 * np.ones((self.K, self.K)))
Beispiel #9
0
    def resample(self, data=[]):
        """
        Resample the
        : param data: a TxKxKxB array of parents. T time bins, K processes,
                     K parent processes, and B bases for each parent process.
        """
        assert data is None or isinstance(data, list)

        mu_post, lmbda_post, alpha_post, beta_post = self._get_conditional_distribution(
            data)

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(mu_post, lmbda_post, alpha_post, beta_post)

        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()
Beispiel #10
0
    def resample(self, data=[]):
        # get posterior gamma distribution shapes
        mu_post, tau_post = self._get_conditional_distribution(data)

        # check
        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()

        self.mu = mu_post
        self.tau = tau_post

        mu_post, lmbda_post, alpha_post, beta_post = self._get_conditional_distribution(
            data)

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(mu_post, lmbda_post, alpha_post, beta_post)

        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()
Beispiel #11
0
    def resample(self, data=[]):
        """
        Resample the
        :param data: a TxKxKxB array of parents. T time bins, K processes,
                     K parent processes, and B bases for each parent process.
        """
        mu_0, lmbda_0, alpha_0, beta_0 = self.mu_0, self.lmbda_0, self.alpha_0, self.beta_0
        assert data is None or isinstance(data, list)

        # 0: count, # 1: Sum of scaled dt, #2: Sum of sq scaled dt
        ss = np.zeros((3, self.K, self.K))
        for d in data:
            ss += d.compute_imp_suff_stats()

        n = ss[0]
        xbar = np.nan_to_num(ss[1] / n)
        xvar = ss[2]

        alpha_post = alpha_0 + n / 2.
        # beta_post = beta_0 + 0.5 * xvar
        # beta_post += 0.5 * lmbda_0 * n / (lmbda_0 + n) * (xbar-mu_0)**2
        beta_post = beta_0 + 0.5 * xvar + 0.5 * lmbda_0 * n * (
            xbar - mu_0)**2 / (lmbda_0 + n)

        lmbda_post = lmbda_0 + n
        mu_post = (lmbda_0 * mu_0 + n * xbar) / (lmbda_0 + n)

        from pyhawkes.utils.utils import sample_nig
        self.mu, self.tau = \
            sample_nig(mu_post, lmbda_post, alpha_post, beta_post)

        # Z is parent
        # C is process
        # S is event time
        S = [x.S for x in self.model.data_list]
        C = [x.C for x in self.model.data_list]
        Z = [x.Z for x in self.model.data_list]
        N_pts = 50
        t = np.linspace(0, self.dt_max, N_pts)
        pt = np.zeros(N_pts)
        normal_sig = self.normal_sig
        normal_mu = self.normal_mu
        pt_prior = np.exp(-(t - normal_mu)**2 / (2 * normal_sig**2)) / np.sqrt(
            2 * np.pi * normal_sig**2)
        dt_max = self.dt_max
        for k1 in range(self.K):
            for k2 in range(self.K):
                tt = np.zeros(N_pts)
                gt = np.ones(N_pts)
                for i in range(len(S)):
                    s, c, z = S[i], C[i], Z[i]
                    cind, pind = (c == k2), (c[z] == k1)
                    igmask = (z != -1)  # no parent
                    inds = cind & pind & igmask
                    if ~np.all(~inds):
                        ds = s[inds] - s[z[inds]]
                        '''
                        if min(ds) < min(t):
                            print k1,k2
                            exit(0)
                        '''
                        ll = -utils.logit(
                            np.absolute(ds[None, :] - t[:, None]), dt_max)
                        # logit grows too fast
                        ll = np.minimum(ll, 100)
                        ll = np.maximum(ll, -100)
                        ll = (ll * self.tau[k1][k2] / 2 - self.mu[k1][k2])**2
                        tt = tt + np.sum(ll, 1)
                        gt[t > min(ds)] = 0.0
                tt = np.cumsum(pt_prior * np.exp(tt - np.max(tt)) * gt)
                if (tt == 0).all():
                    self.delay[k1][k2] = 0
                    #tt = np.cumsum(pt_prior)
                    #delay =  t[np.flatnonzero(tt > np.random.uniform(0,tt[-1]))[0]]
                    #self.delay[k1][k2] = delay
                else:
                    # exp grows too fast, normalize by e^-max(tt)
                    delay = -t[np.flatnonzero(
                        tt > np.random.uniform(0, tt[-1]))[0]]
                    self.delay[k1][k2] = delay

        assert np.isfinite(self.mu).all()
        assert np.isfinite(self.tau).all()