コード例 #1
0
    def test_HawkesKernelExp_str(self):
        """...Test HawkesKernelExp string representation
        """
        intensity = 3
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str(hawkes_kernel_exp), "3 * 2 * exp(- 2 * t)")

        intensity = 3
        decay = 0
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str(hawkes_kernel_exp), "3")

        intensity = 0
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str(hawkes_kernel_exp), "0")
コード例 #2
0
    def test_HawkesKernelExp_repr(self):
        """...Test HawkesKernelExp string in list representation
        """
        intensity = 3
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str([hawkes_kernel_exp]), "[3*2*exp(-2*t)]")

        intensity = 3
        decay = 0
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str([hawkes_kernel_exp]), "[3]")

        intensity = 0
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(str([hawkes_kernel_exp]), "[0]")
コード例 #3
0
    def setUp(self):
        self.decay = 2
        self.intensity = 3
        self.hawkes_kernel_exp = HawkesKernelExp(self.intensity, self.decay)

        self.multiplier = 0.1
        self.cutoff = 0.01
        self.exponent = 1.2
        self.support = 10000
        self.hawkes_kernel_power_law = HawkesKernelPowerLaw(
            self.multiplier, self.cutoff, self.exponent, self.support)
コード例 #4
0
    def setUp(self):
        np.random.seed(28374)

        self.kernels = np.array([[HawkesKernel0(),
                                  HawkesKernelExp(0.1, 3)],
                                 [
                                     HawkesKernelPowerLaw(0.2, 4, 2),
                                     HawkesKernelSumExp([0.1, 0.4], [3, 4])
                                 ]])

        self.baseline = np.random.rand(2)
コード例 #5
0
    def test_HawkesKernelExp_pickle(self):
        """...Test pickling ability of HawkesKernelExp
        """
        obj = HawkesKernelExp(decay=2, intensity=3)
        pickled = pickle.loads(pickle.dumps(obj))

        self.assertTrue(str(obj) == str(pickled))
        self.assertEqual(obj.decay, pickled.decay)
        self.assertEqual(obj.intensity, pickled.intensity)
        np.testing.assert_array_equal(obj.get_values(self.random_times),
                                      obj.get_values(self.random_times))
コード例 #6
0
ファイル: utils.py プロジェクト: xiawenwen49/GNPP_code
    def simulate_hawkes(self, model_name):
        self.model_name = model_name

        def y_func_pos(t_values):
            y_values = 0.02 * np.exp(-t_values)
            return y_values

        def y_func_neg(t_values):
            y_values = -0.1 * np.exp(-t_values)
            return y_values

        if model_name == 'hawkes_neg':
            y_func = y_func_neg
        elif model_name == 'hawkes_pos':
            y_func = y_func_pos

        t_values = np.linspace(0, 101, 100)
        y_values = y_func(t_values)
        tf = TimeFunction([t_values, y_values],
                          inter_mode=TimeFunction.InterLinear,
                          dt=0.1)

        tf_kernel = HawkesKernelTimeFunc(tf)

        N_enodes = self.G_e2n.number_of_nodes()  # regarded as 'N_enodes' types

        base_int = 0.2
        baselines = [base_int for i in range(N_enodes)]
        kernels = [[] for i in range(N_enodes)]
        for i in range(N_enodes):
            for j in range(N_enodes):
                if i == j:
                    # kernels[i].append(HawkesKernel0())
                    kernels[i].append(HawkesKernelExp(.1, 4))  # self influence
                else:
                    if self.G_e2n.has_edge(self.idx_elabel_map[i],
                                           self.idx_elabel_map[j]):
                        kernels[i].append(tf_kernel)
                    else:
                        kernels[i].append(HawkesKernel0())

        hawkes = SimuHawkes(kernels=kernels,
                            baseline=baselines,
                            verbose=False,
                            seed=self.seed)
        hawkes.threshold_negative_intensity(allow=True)

        run_time = 100
        hawkes.end_time = run_time
        hawkes.simulate()
        timestamps = hawkes.timestamps

        self.save(timestamps, self.model_name)
コード例 #7
0
    def test_HawkesKernelExp_strtex(self):
        """...Test HawkesKernelExp latex string representation
        """
        decay = 2
        intensity = 3
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$6 e^{-2 t}$")

        intensity = 3
        decay = 0
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$3$")

        intensity = 0
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$0$")

        intensity = 0.5
        decay = 2
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$e^{-2 t}$")

        decay = 1
        intensity = 3
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$3 e^{- t}$")

        decay = 1
        intensity = 1
        hawkes_kernel_exp = HawkesKernelExp(intensity, decay)
        self.assertEqual(hawkes_kernel_exp.__strtex__(), "$e^{-t}$")
コード例 #8
0
    def test_hawkes_negative_intensity_fail(self):
        """...Test simulation with negative kernel without threshold_negative_intensity
        """
        run_time = 40

        hawkes = SimuHawkes(n_nodes=1, end_time=run_time, verbose=False,
                            seed=1398)
        kernel = HawkesKernelExp(-1.3, .8)
        hawkes.set_kernel(0, 0, kernel)
        hawkes.set_baseline(0, 0.3)

        msg = 'Simulation stopped because intensity went negative ' \
              '\(you could call ``threshold_negative_intensity`` to allow it\)'
        with self.assertRaisesRegex(RuntimeError, msg):
            hawkes.simulate()
コード例 #9
0
    def setUp(self):
        np.random.seed(28374)

        self.kernels = np.array([
            [HawkesKernel0(), HawkesKernelExp(0.1, 3)],
            [HawkesKernelPowerLaw(0.2, 4, 2),
             HawkesKernelSumExp([0.1, 0.4], [3, 4])]
        ])

        t_values = np.linspace(0, 10, 10)
        y_values = np.maximum(0.5 + np.sin(t_values), 0)
        self.time_func_kernel = HawkesKernelTimeFunc(t_values=t_values,
                                                     y_values=y_values)

        self.baseline = np.random.rand(2)
コード例 #10
0
    def test_simu_hawkes_force_simulation(self):
        """...Test force_simulation parameter of SimuHawkes
        """
        diverging_kernel = [[HawkesKernelExp(2, 3)]]
        hawkes = SimuHawkes(kernels=diverging_kernel, baseline=[1],
                            verbose=False)
        hawkes.end_time = 10

        msg = '^Simulation not launched as this Hawkes process is not ' \
              'stable \(spectral radius of 2\). You can use ' \
              'force_simulation parameter if you really want to simulate it$'
        with self.assertRaisesRegex(ValueError, msg):
            hawkes.simulate()

        msg = "^This process has already be simulated until time 0.000000$"
        with self.assertWarnsRegex(UserWarning, msg):
            hawkes.end_time = 0
            hawkes.force_simulation = True
            hawkes.simulate()
コード例 #11
0
def generate_points(n_processes, mu, alpha, decay, window, seed, dt=0.01):
    """
    Generates points of an marked Hawkes processes using the tick library
    """
    hawkes = SimuHawkes(n_nodes=n_processes,
                        end_time=window,
                        verbose=False,
                        seed=seed)
    for i in range(n_processes):
        for j in range(n_processes):
            hawkes.set_kernel(i=i,
                              j=j,
                              kernel=HawkesKernelExp(intensity=alpha[i][j] /
                                                     decay[i][j],
                                                     decay=decay[i][j]))
        hawkes.set_baseline(i, mu[i])

    hawkes.track_intensity(dt)
    hawkes.simulate()
    return hawkes.timestamps
コード例 #12
0
    def test_hawkes_negative_intensity(self):
        """...Test simulation with negative kernel
        """
        run_time = 40

        hawkes = SimuHawkes(n_nodes=1, end_time=run_time, verbose=False,
                            seed=1398)
        kernel = HawkesKernelExp(-1.3, .8)
        hawkes.set_kernel(0, 0, kernel)
        hawkes.set_baseline(0, 0.3)
        hawkes.threshold_negative_intensity()

        dt = 0.1
        hawkes.track_intensity(dt)
        hawkes.simulate()

        self.assertAlmostEqual(hawkes.tracked_intensity[0].min(), 0)
        self.assertAlmostEqual(hawkes.tracked_intensity[0].max(),
                               hawkes.baseline[0])
        self.assertGreater(hawkes.n_total_jumps, 1)
コード例 #13
0
from tick.plot import plot_hawkes_kernels
from tick.hawkes import (SimuHawkes, SimuHawkesMulti, HawkesKernelExp,
                         HawkesKernelTimeFunc, HawkesKernelPowerLaw,
                         HawkesKernel0, HawkesSumGaussians)

end_time = 1000
n_nodes = 2
n_realizations = 10
n_gaussians = 5

timestamps_list = []

kernel_timefunction = HawkesKernelTimeFunc(
    t_values=np.array([0., .7, 2.5, 3., 4.]),
    y_values=np.array([.3, .03, .03, .2, 0.]))
kernels = [[HawkesKernelExp(.2, 2.),
            HawkesKernelPowerLaw(.2, .5, 1.3)],
           [HawkesKernel0(), kernel_timefunction]]

hawkes = SimuHawkes(baseline=[.5, .2],
                    kernels=kernels,
                    end_time=end_time,
                    verbose=False,
                    seed=1039)

multi = SimuHawkesMulti(hawkes, n_simulations=n_realizations)

multi.simulate()

learner = HawkesSumGaussians(n_gaussians, max_iter=10)
learner.fit(multi.timestamps)
コード例 #14
0
import numpy as np
import matplotlib.pyplot as plt

from tick.hawkes import HawkesKernel0, HawkesKernelExp, HawkesKernelPowerLaw, \
    HawkesKernelTimeFunc

kernel_0 = HawkesKernel0()
kernel_exp = HawkesKernelExp(.7, 1.3)
kernel_pl = HawkesKernelPowerLaw(.1, .2, 0.7)

t_values = np.array([0, 1, 1.5, 1.8, 2.7])
y_values = np.array([0, .6, .34, .2, .1])
kernel_tf = HawkesKernelTimeFunc(t_values=t_values, y_values=y_values)

kernels = [[kernel_0, kernel_exp], [kernel_pl, kernel_tf]]

fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(10, 4))

t_values = np.linspace(0, 3, 100)
for i in range(2):
    for j in range(2):
        ax[i, j].plot(t_values, kernels[i][j].get_values(t_values),
                      label=kernels[i][j])
        ax[i, j].legend()
plt.show()
コード例 #15
0
 def setUp(self):
     self.decay = 2
     self.intensity = 3
     self.hawkes_kernel_exp = HawkesKernelExp(self.intensity, self.decay)
コード例 #16
0
                   inter_mode=TimeFunction.InterConstRight,
                   dt=0.1)
kernel1 = HawkesKernelTimeFunc(tf1)

t_values2 = np.linspace(0, 4, 20)
y_values2 = np.maximum(0., np.sin(t_values2) / 4)
tf2 = TimeFunction([t_values2, y_values2])
kernel2 = HawkesKernelTimeFunc(tf2)

baseline = np.array([0.1, 0.3])

hawkes = SimuHawkes(baseline=baseline,
                    end_time=run_time,
                    verbose=False,
                    seed=2334)

hawkes.set_kernel(0, 0, kernel1)
hawkes.set_kernel(0, 1, HawkesKernelExp(.5, .7))
hawkes.set_kernel(1, 1, kernel2)

hawkes.simulate()

em = HawkesEM(4, kernel_size=16, n_threads=8, verbose=False, tol=1e-3)
em.fit(hawkes.timestamps)

fig = plot_hawkes_kernels(em, hawkes=hawkes, show=False)

for ax in fig.axes:
    ax.set_ylim([0, 1])
plt.show()
コード例 #17
0
def test_HawkesEM():

    print('\n##############################')
    print('\nstarting: test_HawkesEM()\n')

    run_time = 30000

    t_values1 = np.array([0, 1, 1.5, 2., 3.5], dtype=float)
    y_values1 = np.array([0, 0.2, 0, 0.1, 0.], dtype=float)
    tf1 = TimeFunction([t_values1, y_values1],
                       inter_mode=TimeFunction.InterConstRight,
                       dt=0.1)
    kernel1 = HawkesKernelTimeFunc(tf1)

    t_values2 = np.linspace(0, 4, 20)
    y_values2 = np.maximum(0., np.sin(t_values2) / 4)
    tf2 = TimeFunction([t_values2, y_values2])
    kernel2 = HawkesKernelTimeFunc(tf2)

    baseline = np.array([0.1, 0.3])

    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
    realizations = list()
    for i in range(0, 1000):

        print('')

        temp_seed = int(1000 + 1000 * random.random())
        print('i = ' + str(i) + ', temp_seed = ' + str(temp_seed))

        hawkes = SimuHawkes(baseline=baseline,
                            end_time=run_time,
                            verbose=False,
                            seed=temp_seed)
        hawkes.set_kernel(0, 0, kernel1)
        hawkes.set_kernel(0, 1, HawkesKernelExp(.5, .7))
        hawkes.set_kernel(1, 1, kernel2)
        hawkes.simulate()

        temp_realization = hawkes.timestamps
        print('i = ' + str(i) + ', ' + 'event counts = (' +
              str(len(temp_realization[0])) + ',' +
              str(len(temp_realization[1])) + ')')
        print(temp_realization)

        realizations.append(temp_realization)

    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
    em = HawkesEM(4, kernel_size=16, n_threads=8, verbose=False, tol=1e-3)
    em.fit(events=realizations)

    fig = plot_hawkes_kernels(em, hawkes=hawkes, show=False)

    outputFILE = 'test-HawkesEM.png'
    for ax in fig.axes:
        ax.set_ylim([0, 1])
    plt.savefig(fname=outputFILE, bbox_inches='tight', pad_inches=0.2)

    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
    print('\nexitng: test_HawkesEM()')
    print('\n##############################')

    return (None)
コード例 #18
0
t_values = np.array([0, 1, 1.5], dtype=float)
y_values = np.array([0, .2, 0], dtype=float)
tf1 = TimeFunction([t_values, y_values],
                   inter_mode=TimeFunction.InterConstRight,
                   dt=0.1)
kernel_1 = HawkesKernelTimeFunc(tf1)

t_values = np.array([0, .1, 2], dtype=float)
y_values = np.array([0, .4, -0.2], dtype=float)
tf2 = TimeFunction([t_values, y_values],
                   inter_mode=TimeFunction.InterLinear,
                   dt=0.1)
kernel_2 = HawkesKernelTimeFunc(tf2)

hawkes = SimuHawkes(kernels=[[kernel_1, kernel_1],
                             [HawkesKernelExp(.07, 4), kernel_2]],
                    baseline=[1.5, 1.5],
                    verbose=False,
                    seed=23983)

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

fig, ax = plt.subplots(hawkes.n_nodes, 1, figsize=(14, 8))
plot_point_process(hawkes, t_max=20, ax=ax)

plt.show()
コード例 #19
0
initparam = [np.log(0.5), 0, 0, 0, 0]
nTrain = 100
nTest = 1000

# Kernel Param -------------------------------------------

mu = 1.
param = [None] * Kclass
param[0] = np.array([mu, 0.7, 1.3])
param[1] = np.array([mu, 0.2, 3])

kernelSim = [None] * Kclass
kernelBayes = [None] * Kclass

for k in range(Kclass):
    kernelSim[k] = HawkesKernelExp(param[k][1], param[k][2])
    kernelBayes[k] = kernelSim[k].get_values

##############################################################
# Risks computation -------------------------------------------
##############################################################

# TrainSample
listJumptimesTrain, Ytrain = simulHawkesTraj(Klass=Kclass,
                                             mu=mu,
                                             Tmax=Tmax,
                                             nSample=nTrain,
                                             kernelSim=kernelSim)
# TestSample
listJumptimesTest, Ytest = simulHawkesTraj(Klass=Kclass,
                                           mu=mu,