示例#1
0
def __simulate_statistics(mus, alphas, betas):
    # simulate next time_span statistics
    simu_params = SimuHawkesExpKernels(adjacency=alphas,
                                       decays=betas,
                                       baseline=mus,
                                       end_time=SIMU_END,
                                       verbose=False)
    if simu_params.spectral_radius() > 1.:
        return None
    multi = SimuHawkesMulti(simu_params, n_simulations=N_REALIZATIONS)
    multi.simulate()
    # check simulated statistics
    count_statistics = [[], [], [], []]
    interarrival_statistics = [[], [], [], []]
    for realization in multi.timestamps:
        for dim_i, dim in enumerate(realization):
            dim_statistics = __get_statistic(dim)
            count_statistics[dim_i].append(dim_statistics["counts"])
            interarrival_statistics[dim_i].append(
                dim_statistics["interarrival"])
    result_dict = {
        "counts": np.mean(count_statistics, axis=1).tolist(),
        "interarrival": interarrival_statistics
    }
    result_list = []
    for dim_i in range(NUMBER_OF_DIMENSIONS):
        result_list.append({
            "counts": result_dict["counts"][dim_i],
            "interarrival": result_dict["interarrival"][dim_i]
        })
    return result_list
示例#2
0
    def setUp(self):
        np.random.seed(23982)
        self.n_nodes = 3
        self.baseline = np.random.rand(self.n_nodes)
        self.adjacency = np.random.rand(self.n_nodes, self.n_nodes) / 2
        self.decays = np.random.rand(self.n_nodes, self.n_nodes)

        self.adjacency[0, 0] = 0
        self.adjacency[-1, -1] = 0

        self.hawkes = SimuHawkesExpKernels(self.adjacency, self.decays,
                                           baseline=self.baseline, seed=203,
                                           verbose=False)
示例#3
0
    def simulate_sparse_realization(self):
        """Simulate realization in which some nodes are sometimes empty
        """
        baseline = np.array([0.3, 0.001])
        adjacency = np.array([[0.5, 0.8], [0., 1.3]])

        sim = SimuHawkesExpKernels(adjacency=adjacency, decays=self.decay,
                                   baseline=baseline, verbose=False,
                                   seed=13487, end_time=500)
        sim.adjust_spectral_radius(0.8)
        multi = SimuHawkesMulti(sim, n_simulations=100)

        adjacency = sim.adjacency
        multi.simulate()

        # Check that some but not all realizations are empty
        self.assertGreater(max(map(lambda r: len(r[1]), multi.timestamps)), 1)
        self.assertEqual(min(map(lambda r: len(r[1]), multi.timestamps)), 0)

        return baseline, adjacency, multi.timestamps
示例#4
0
    def test_solver_scpg(self):
        """...Check Self-concordant proximal gradient solver for a Hawkes
        model with ridge penalization
        """
        beta = 3
        betas = beta * np.ones((2, 2))

        alphas = np.zeros((2, 2))

        alphas[0, 0] = 1
        alphas[0, 1] = 2
        alphas[1, 1] = 3

        mus = np.arange(1, 3) / 3

        hawkes = SimuHawkesExpKernels(adjacency=alphas, decays=betas,
                                      baseline=mus, seed=1231, end_time=20000,
                                      verbose=False)
        hawkes.adjust_spectral_radius(0.8)
        alphas = hawkes.adjacency

        hawkes.simulate()
        timestamps = hawkes.timestamps

        model = ModelHawkesFixedExpKernLogLik(beta).fit(timestamps)
        prox = ProxL2Sq(1e-7, positive=True)
        pg = SCPG(max_iter=2000, tol=1e-10, verbose=False,
                  step=1e-5).set_model(model).set_prox(prox)

        pg.solve(np.ones(model.n_coeffs))

        original_coeffs = np.hstack((mus, alphas.reshape(4)))
        np.testing.assert_array_almost_equal(pg.solution, original_coeffs,
                                             decimal=2)
示例#5
0
    def test_hawkes_set_timestamps(self):
        """...Test simulation after some timestamps have been set manually
        """
        decay = 0.5
        baseline = [0.2, 0.4]
        adjacency = [[0.2, 0.1], [0, 0.3]]

        hawkes = SimuHawkesExpKernels(baseline=baseline,
                                      decays=decay,
                                      adjacency=adjacency,
                                      verbose=False,
                                      seed=1393)

        # timestamps generated by a hawkes process with the same
        # characteristics simulated up to time 10
        original_timestamps = [
            np.array([7.096244, 9.389927]),
            np.array([
                0.436199, 0.659153, 2.622352, 3.095093, 7.189881, 8.068153,
                9.240032
            ]),
        ]

        hawkes.track_intensity(1)
        hawkes.set_timestamps(original_timestamps, 10)
        hawkes.end_time = 100
        hawkes.simulate()

        # Intensity up to time 10 is known
        first_intensities = hawkes.tracked_intensity[0][:10]
        np.testing.assert_array_almost_equal(first_intensities, [
            0.2, 0.2447256, 0.27988282, 0.24845138, 0.23549475, 0.27078386,
            0.26749709, 0.27473586, 0.24532959, 0.22749379
        ])

        # Ensure other jumps have occured afterwards
        self.assertGreater(hawkes.n_total_jumps,
                           sum(map(len, original_timestamps)))
示例#6
0
    def get_train_data(n_nodes=3, betas=1.):
        np.random.seed(130947)
        baseline = np.random.rand(n_nodes)
        adjacency = np.random.rand(n_nodes, n_nodes)
        if isinstance(betas, (int, float)):
            betas = np.ones((n_nodes, n_nodes)) * betas

        sim = SimuHawkesExpKernels(adjacency=adjacency, decays=betas,
                                   baseline=baseline, verbose=False,
                                   seed=13487, end_time=3000)
        sim.adjust_spectral_radius(0.8)
        adjacency = sim.adjacency
        sim.simulate()

        return sim.timestamps, baseline, adjacency
示例#7
0
class Test(unittest.TestCase):
    def setUp(self):
        np.random.seed(23982)
        self.n_nodes = 3
        self.baseline = np.random.rand(self.n_nodes)
        self.adjacency = np.random.rand(self.n_nodes, self.n_nodes) / 2
        self.decays = np.random.rand(self.n_nodes, self.n_nodes)

        self.adjacency[0, 0] = 0
        self.adjacency[-1, -1] = 0

        self.hawkes = SimuHawkesExpKernels(self.adjacency, self.decays,
                                           baseline=self.baseline, seed=203,
                                           verbose=False)

    def test_hawkes_exponential_kernels(self):
        """...Test creation of a Hawkes Process with exponential kernels
        """

        kernel_0 = None
        for i, j in product(range(self.n_nodes), range(self.n_nodes)):
            kernel_ij = self.hawkes.kernels[i, j]

            if self.adjacency[i, j] == 0:
                self.assertEqual(kernel_ij.__class__, HawkesKernel0)

                # We check that all 0 adjacency share the same kernel 0
                # This might save lots of memory with very large,
                # very sparse adjacency matrices
                if kernel_0 is None:
                    kernel_0 = kernel_ij
                else:
                    self.assertEqual(kernel_0, kernel_ij)

            else:
                self.assertEqual(kernel_ij.__class__, HawkesKernelExp)
                self.assertEqual(kernel_ij.decay, self.decays[i, j])
                self.assertEqual(kernel_ij.intensity, self.adjacency[i, j])

        np.testing.assert_array_equal(self.baseline, self.hawkes.baseline)

    def test_hawkes_spectral_radius_exp_kernel(self):
        """...Hawkes Process spectral radius and adjust spectral radius
        methods
        """
        self.assertAlmostEqual(self.hawkes.spectral_radius(),
                               0.6645446549735008)

        self.hawkes.adjust_spectral_radius(0.6)
        self.assertAlmostEqual(self.hawkes.spectral_radius(), 0.6)

    def test_hawkes_mean_intensity(self):
        """...Test that Hawkes obtained mean intensity is consistent
        """

        self.assertLess(self.hawkes.spectral_radius(), 1)

        self.hawkes.end_time = 1000
        self.hawkes.track_intensity(0.01)
        self.hawkes.simulate()

        mean_intensity = self.hawkes.mean_intensity()
        for i in range(self.hawkes.n_nodes):
            self.assertAlmostEqual(np.mean(self.hawkes.tracked_intensity[i]),
                                   mean_intensity[i], delta=0.1)
示例#8
0
 def _corresponding_simu(self):
     return SimuHawkesExpKernels(adjacency=self.adjacency,
                                 decays=self.decays,
                                 baseline=self.baseline)
示例#9
0
 def _corresponding_simu(self):
     """Create simulation object corresponding to the obtained coefficients
     """
     return SimuHawkesExpKernels(adjacency=self.adjacency,
                                 decays=self.decay,
                                 baseline=self.baseline)
示例#10
0
from tick.plot import plot_hawkes_kernel_norms
from tick.simulation import SimuHawkesExpKernels, SimuHawkesMulti
from tick.inference import HawkesADM4

end_time = 10000
n_realizations = 5
decay = 3.

baseline = np.ones(6) * .03
adjacency = np.zeros((6, 6))
adjacency[2:, 2:] = np.ones((4, 4)) * 0.1
adjacency[:3, :3] = np.ones((3, 3)) * 0.15

hawkes_exp_kernels = SimuHawkesExpKernels(adjacency=adjacency,
                                          decays=decay,
                                          baseline=baseline,
                                          end_time=end_time,
                                          verbose=False,
                                          seed=1039)

multi = SimuHawkesMulti(hawkes_exp_kernels, n_simulations=n_realizations)

multi.end_time = [(i + 1) / n_realizations * end_time
                  for i in range(n_realizations)]
multi.simulate()

learner = HawkesADM4(decay)
learner.fit(multi.timestamps)

plot_hawkes_kernel_norms(learner)
示例#11
0
Simulation of 3-dimensional hawkes process
==========================================
"""
import numpy as np
import matplotlib.pyplot as plt

from tick.simulation import SimuHawkesExpKernels
from tick.plot import plot_point_process

n_nodes = 3  # dimension of the Hawkes process
adjacency = 0.2 * np.ones((n_nodes, n_nodes))
adjacency[0, 1] = 0
decays = 3 * np.ones((n_nodes, n_nodes))
baseline = 0.5 * np.ones(n_nodes)
hawkes = SimuHawkesExpKernels(adjacency=adjacency,
                              decays=decays,
                              baseline=baseline,
                              verbose=False,
                              seed=2398)

run_time = 100
hawkes.end_time = run_time
dt = 0.01
hawkes.track_intensity(dt)
hawkes.simulate()

fig, ax = plt.subplots(n_nodes, 1, figsize=(16, 8), sharex=True, sharey=True)
plot_point_process(hawkes, n_points=50000, t_min=10, max_jumps=30, ax=ax)
fig.tight_layout()
plt.show()