Exemplo n.º 1
0
    def test_values(self):
        """...Test that TimeFunction returns correct values on randomly
        selected times
        """
        for t_array, y_array, inter_mode in self.samples:
            # take random t on TimeFunction support
            t_inside_support = np.random.uniform(t_array[0], t_array[-1], 10)
            t_before_support = np.random.uniform(t_array[0] - 4, t_array[0], 5)
            t_after_support = np.random.uniform(t_array[-1], t_array[-1] + 4,
                                                5)

            test_t = np.hstack(
                (t_before_support, t_inside_support, t_after_support, t_array))
            true_values = dichotomic_value(test_t,
                                           t_array,
                                           y_array,
                                           inter_mode=inter_mode)

            tf = TimeFunction([t_array, y_array], inter_mode=inter_mode)
            tf_values = tf.value(test_t)
            errors = np.abs(true_values - tf_values)

            # If we do not find the same value ensure that the error is
            # controlled by max_error
            different_values = errors > 1e-6

            for t, error in zip(test_t[different_values],
                                errors[different_values]):
                if inter_mode == TimeFunction.InterLinear:
                    self.assertLess(error, tf._max_error(t))
                else:
                    distance_point = np.array(t - t_array).min()
                    self.assertLess(distance_point, tf.dt)
Exemplo n.º 2
0
    def test_simulation_1d_inhomogeneous_poisson(self):
        """...Test if simulation of a 1d inhomogeneous Poisson process
        No statistical guarantee on the result"""

        run_time = 30

        t_values = np.linspace(0, run_time - 3, 100)
        y_values = np.maximum(0.5 + np.sin(t_values), 0)

        tf = TimeFunction((t_values, y_values))
        tf_zero = TimeFunction(0)

        inhomo_poisson_process = SimuInhomogeneousPoisson([tf, tf_zero],
                                                          seed=2937,
                                                          end_time=run_time,
                                                          verbose=False)
        inhomo_poisson_process.simulate()

        timestamps = inhomo_poisson_process.timestamps

        # Ensure that non zero TimeFunction intensity ticked at least 2 times
        self.assertGreater(len(timestamps[0]), 2)
        # Ensure that zero TimeFunction intensity never ticked
        self.assertEqual(len(timestamps[1]), 0)

        # Ensure that intensity was non zero when the process did tick
        self.assertEqual(np.prod(tf.value(timestamps[0]) > 0), 1)
Exemplo n.º 3
0
    def test_simu_hawkes_multi_time_func(self):
        """...Test that hawkes multi works correctly with HawkesKernelTimeFunc
        """
        run_time = 100

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

        t_values2 = np.array([0, 2, 2.5], dtype=float)
        y_values2 = np.array([0, .6, 0], dtype=float)
        tf2 = TimeFunction([t_values2, y_values2],
                           inter_mode=TimeFunction.InterConstRight, dt=0.1)
        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, kernel1)
        hawkes.set_kernel(1, 0, kernel2)
        hawkes.set_kernel(1, 1, kernel2)

        hawkes_multi = SimuHawkesMulti(hawkes, n_simulations=5, n_threads=4)
        hawkes_multi.simulate()
Exemplo n.º 4
0
    def test_cyclic(self):
        """...Test cyclic border type
        """
        last_value = 2.3
        T = np.linspace(0, last_value)
        Y = np.cos(T * np.pi)

        tf = TimeFunction([T, Y], border_type=TimeFunction.Cyclic)

        self.assertAlmostEqual(tf.value(0.3), tf.value(last_value + 0.3),
                               delta=1e-8)
Exemplo n.º 5
0
 def test_hawkes_set_baseline_timefunction(self):
     """...Test Hawkes process baseline set with TimeFunction
     """
     t_values = [0.5, 1., 2., 3.5]
     y_values_1 = [1., 2., 1.5, 4.]
     y_values_2 = [2., 1.5, 4., 1.]
     timefunction1 = TimeFunction((t_values, y_values_1))
     timefunction2 = TimeFunction((t_values, y_values_2))
     hawkes = SimuHawkes(baseline=[timefunction1, timefunction2],
                         kernels=self.kernels, verbose=False)
     hawkes.end_time = 10
     hawkes.simulate()
     self.assertGreater(hawkes.n_total_jumps, 1)
Exemplo n.º 6
0
    def test_pickle(self):
        """...Test TimeFunction's pickling ability
        """
        T = np.array([0.0, 1.0,  2.0])
        Y = np.array([1.0, 0.0, -1.0])

        tf = TimeFunction([T, Y], inter_mode=TimeFunction.InterLinear, dt=0.2)

        recon = pickle.loads(pickle.dumps(tf))

        self.assertEqual(tf.value(1), recon.value(1))
        self.assertEqual(tf.value(2), recon.value(2))
        self.assertEqual(tf.value(1.5), recon.value(1.5))
        self.assertEqual(tf.value(0.75), recon.value(0.75))
Exemplo n.º 7
0
    def simulate_poisson(self):
        " inhomogeneous poisson process "
        self.model_name = 'poisson'

        run_time = 100
        T = np.arange((run_time * 0.9) * 5, dtype=float) / 5
        Y = np.maximum(
            15 * np.sin(T) * (np.divide(np.ones_like(T),
                                        np.sqrt(T + 1) + 0.1 * T)), 0.001)

        tf = TimeFunction((T, Y), dt=0.01)

        # We define a 1 dimensional inhomogeneous Poisson process with the intensity function seen above
        timestamps = []
        for i, edge in enumerate(self.G_e2n.nodes):
            in_poi = SimuInhomogeneousPoisson([tf],
                                              end_time=run_time,
                                              verbose=False,
                                              seed=self.seed + i)

            # We activate intensity tracking and launch simulation
            # in_poi.track_intensity(0.1)
            in_poi.simulate()
            ts = in_poi.timestamps[0]
            timestamps.append(ts)

        self.save(timestamps, self.model_name)
Exemplo n.º 8
0
def simulate_NHP(run_time, T, Y, dt_, track):
    #run_time = 30

    #T = np.arange((run_time * 0.9) * 5, dtype=float) / 5
    #Y = np.maximum(
    #    15 * np.sin(T) * (np.divide(np.ones_like(T),
    #                                np.sqrt(T + 1) + 0.1 * T)), 0.001)

    tf = TimeFunction((T, Y), dt=dt_)

    # We define a 1 dimensional inhomogeneous Poisson process with the
    # intensity function seen above
    in_poi = SimuInhomogeneousPoisson([tf],
                                      end_time=run_time,
                                      verbose=True,
                                      seed=3)  #, max_jumps=sum(Y))

    # We activate intensity tracking and launch simulation
    in_poi.track_intensity(track)
    in_poi.threshold_negative_intensity(allow=True)

    in_poi.simulate()

    # We plot the resulting inhomogeneous Poisson process with its
    # intensity and its ticks over time
    plot_point_process(in_poi)
    return list(in_poi.tracked_intensity[0]), list(
        in_poi.intensity_tracked_times)
Exemplo n.º 9
0
    def simulate_new_set_of_trips(self):

        from tick.base import TimeFunction
        from tick.hawkes import SimuInhomogeneousPoisson

        df = self.df
        df['hod'] = [r.hour for r in df['Trans DateDT']]
            
        rate_per_hour = df.groupby(['hod']).agg({"lat":len}).rename(columns={'lat': 'hourSum'})
        rate_per_hour['normalizedHourSum'] = rate_per_hour.hourSum / np.sum(rate_per_hour.hourSum)
        rate_per_hour['scaled_by_hours'] = rate_per_hour.normalizedHourSum / 125.53819444444444

        hour_to_base_rate_dict = rate_per_hour[['scaled_by_hours']].to_dict()['scaled_by_hours']
        base_rates = np.array(list(hour_to_base_rate_dict.values()))

        total_per_address = df.groupby(['formatted_address']).agg({"lat":len}).rename(columns={'lat': 'formatted_addressSum'})

        simulated_data = []
        print('Simulating...')
        c = 0
        addresses = pd.Series.unique(df.formatted_address)
        for add in addresses:
            c += 1
            total_per_address_i = 1000
            loc_base_rates = base_rates * total_per_address_i
            T = []
            Y = []
            hour_count = 0
            while hour_count < 3001 + 1:
                T.append(hour_count)
                Y.append(loc_base_rates[hour_count % 24])

                hour_count = hour_count + 1

            tf = TimeFunction((T, Y), dt=0.1)
            run_time = 3001
            in_poi = SimuInhomogeneousPoisson([tf], end_time=run_time, verbose=False)
            in_poi.track_intensity(0.1)
            in_poi.simulate()
            for h in in_poi.timestamps[0]:
                ts = self.START_TIMESTAMP + h * 3600
                simulated_data.append((add, ts, self.mean_fare_for_address[add]))

        self.simulated_trips_df = pd.DataFrame(simulated_data, columns=['formatted_address', 'ts', 'Fare excl'])
        self.simulated_trips_df = self.simulated_trips_df.sort_values(by='ts')
        self.simulated_trips_df['Trans DateDT'] = pd.to_datetime(self.simulated_trips_df['ts'], unit='s')

        x = pd.DatetimeIndex(self.simulated_trips_df['Trans DateDT'])
        y = x.tz_localize('UTC', ambiguous='NaT')
        y = y.tz_convert('Pacific/Auckland')

        self.simulated_trips_df['Trans DateDT'] = y
        self.simulated_trips_df = self.simulated_trips_df[~self.simulated_trips_df['Trans DateDT'].isnull()].copy()

        self.simulated_trips_df['dt_value'] = [np.int64(x.value) for x in list(self.simulated_trips_df['Trans DateDT'])]
        self.simulated_trips_df['ts_recalculated_for_check'] = self.simulated_trips_df.dt_value / 1e9

        self.simulated_trips_df['ts_recalculated_for_check'] = self.simulated_trips_df.ts_recalculated_for_check.astype(int)
        self.simulated_trips_df['ts'] = self.simulated_trips_df.ts.astype(int)
Exemplo n.º 10
0
 def generate_times_opt(max_t, delta, vreme_c, c_var, vreme, Lambda):
     time = np.arange(delta, max_t, delta)
     c_value_t = Simulation.C_interp(time, vreme_c, c_var)
     lamb_val_t = Simulation.Lambda_interp(time, vreme, Lambda) / c_value_t
     tf = TimeFunction((time, lamb_val_t), dt=delta)
     Psim = SimuInhomogeneousPoisson([tf], end_time=max_t, verbose=False)
     Psim.simulate()
     simulacija = Psim.timestamps
     return simulacija[0]
Exemplo n.º 11
0
    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)
Exemplo n.º 12
0
class Test(unittest.TestCase):
    def setUp(self):
        size = 10
        self.y_values = np.random.rand(size)
        self.t_values = np.arange(size, dtype=float)
        self.time_function = TimeFunction([self.t_values, self.y_values])
        self.hawkes_kernel_time_func = HawkesKernelTimeFunc(self.time_function)

    def test_HawkesKernelTimeFunc_time_function(self):
        """...Test HawkesKernelTimeFunc time_function parameter
        """
        t_values = np.linspace(-1, 100, 1000)
        np.testing.assert_array_equal(
            self.hawkes_kernel_time_func.time_function.value(t_values),
            self.time_function.value(t_values))

        self.hawkes_kernel_time_func = \
            HawkesKernelTimeFunc(t_values=self.t_values, y_values=self.y_values)
        np.testing.assert_array_equal(
            self.hawkes_kernel_time_func.time_function.value(t_values),
            self.time_function.value(t_values))

    def test_HawkesKernelTimeFunc_str(self):
        """...Test HawkesKernelTimeFunc string representation
        """
        self.assertEqual(str(self.hawkes_kernel_time_func), "KernelTimeFunc")

    def test_HawkesKernelTimeFunc_repr(self):
        """...Test HawkesKernelTimeFunc string in list representation
        """
        self.assertEqual(str([self.hawkes_kernel_time_func]),
                         "[KernelTimeFunc]")

    def test_HawkesKernelTimeFunc_strtex(self):
        """...Test HawkesKernelTimeFunc string representation
        """
        self.assertEqual(self.hawkes_kernel_time_func.__strtex__(),
                         "TimeFunc Kernel")
Exemplo n.º 13
0
    def test_sample_y(self):
        """...Test that generated sampled_y is correct
        """
        for t_array, y_array, inter_mode in self.samples:
            tf = TimeFunction([t_array, y_array], inter_mode=inter_mode)
            # We remove last value as it is computed but not used
            created_sample_y = tf.sampled_y[:-1]

            sampled_times = t_array[0] + \
                            tf.dt * np.arange(len(created_sample_y))

            true_sample_y = dichotomic_value(
                sampled_times, t_array, y_array, inter_mode=inter_mode)

            np.testing.assert_almost_equal(created_sample_y, true_sample_y)
Exemplo n.º 14
0
def time_funclat(f, support, lat=0, steps=100,
              inter_mode=TimeFunction.InterLinear):
    t_values = np.linspace(0, support, steps + 1)
    y_values = f(t_values)
    if lat > 0:
        t_values_lat = np.linspace(0, lat, num=steps, endpoint=False)
        y_values_lat = np.zeros(steps)
        t_values_shifted = t_values + lat
        t_all = np.concatenate((t_values_lat, t_values_shifted))
        y_all = np.concatenate((y_values_lat, y_values))
    else:
        t_all = t_values.view()
        y_all = y_values.view()
    return TimeFunction(values=(t_all, y_all),
                        border_type=TimeFunction.Border0,
                        inter_mode=inter_mode)
Exemplo n.º 15
0
    def test_simu_hawkes_no_seed(self):
        """...Test hawkes multi can be simulated even if no seed is given
        """
        T1 = np.array([0, 2, 2.5], dtype=float)
        Y1 = np.array([0, .6, 0], dtype=float)
        tf = TimeFunction([T1, Y1], inter_mode=TimeFunction.InterConstRight,
                          dt=0.1)
        kernel = HawkesKernelTimeFunc(tf)
        hawkes = SimuHawkes(baseline=[.1], end_time=100, verbose=False)
        hawkes.set_kernel(0, 0, kernel)
        multi_hawkes_1 = SimuHawkesMulti(hawkes, n_simulations=5)
        multi_hawkes_1.simulate()

        multi_hawkes_2 = SimuHawkesMulti(hawkes, n_simulations=5)
        multi_hawkes_2.simulate()

        # If no seed are given, realizations must be different
        self.assertNotEqual(multi_hawkes_1.timestamps[0][0][0],
                            multi_hawkes_2.timestamps[0][0][0])
    def test_HawkesKernelTimeFunc_pickle(self):
        """...Test pickling ability of HawkesKernelTimeFunc
        """
        size = 10
        y_values = np.random.rand(size)
        t_values = np.arange(size, dtype=float)
        time_function = TimeFunction([t_values, y_values])
        obj = HawkesKernelTimeFunc(time_function)

        pickled = pickle.loads(pickle.dumps(obj))

        self.assertEqual(obj.time_function.value(1),
                         pickled.time_function.value(1))
        self.assertEqual(obj.time_function.value(2),
                         pickled.time_function.value(2))
        self.assertEqual(obj.time_function.value(1.5),
                         pickled.time_function.value(1.5))
        self.assertEqual(obj.time_function.value(0.75),
                         pickled.time_function.value(0.75))
        np.testing.assert_array_equal(obj.get_values(self.random_times),
                                      obj.get_values(self.random_times))
Exemplo n.º 17
0
    def test_track_intensity(self):
        """...Test that point process intensity is tracked correctly
        """
        t_values = np.linspace(0, self.run_time - 3, 100)
        y_values_1 = np.maximum(0.5 + np.sin(t_values), 0)
        y_values_2 = np.maximum(1. / (1 + t_values), 0)

        tf_1 = TimeFunction((t_values, y_values_1))
        tf_2 = TimeFunction((t_values, y_values_2))

        inhomo_poisson_process = SimuInhomogeneousPoisson(
            [tf_1, tf_2], end_time=self.run_time, seed=2937, verbose=False)

        inhomo_poisson_process.track_intensity(0.1)
        inhomo_poisson_process.simulate()

        tracked_intensity = inhomo_poisson_process.tracked_intensity
        intensity_times = inhomo_poisson_process.intensity_tracked_times

        # Ensure that intensity recorded is equal to the given TimeFunction
        np.testing.assert_array_almost_equal(tracked_intensity[0],
                                             tf_1.value(intensity_times))
        np.testing.assert_array_almost_equal(tracked_intensity[1],
                                             tf_2.value(intensity_times))
=====================================

Simulation of Hawkes processes with usage of custom kernels
"""

import matplotlib.pyplot as plt
import numpy as np

from tick.base import TimeFunction
from tick.hawkes import SimuHawkes, HawkesKernelExp, HawkesKernelTimeFunc
from tick.plot import plot_point_process

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)
Exemplo n.º 19
0
    def test_norm(self):
        """...Test TimeFunction's get_norm method on few known examples
        """
        T = np.array([0, 1, 2], dtype=float)
        Y = np.array([1, 0, -1], dtype=float)

        tf = TimeFunction([T, Y],
                          inter_mode=TimeFunction.InterConstLeft,
                          dt=0.5)
        self.assertAlmostEqual(tf.get_norm(), -1)

        tf = TimeFunction([T, Y],
                          inter_mode=TimeFunction.InterConstRight,
                          dt=0.5)
        self.assertAlmostEqual(tf.get_norm(), 1)

        tf = TimeFunction([T, Y], inter_mode=TimeFunction.InterLinear, dt=0.5)
        self.assertAlmostEqual(tf.get_norm(), 0)

        tf = TimeFunction([T, Y],
                          inter_mode=TimeFunction.InterConstLeft,
                          dt=0.3)
        self.assertAlmostEqual(tf.get_norm(), -1.1)

        tf = TimeFunction([T, Y],
                          inter_mode=TimeFunction.InterConstRight,
                          dt=0.3)
        self.assertAlmostEqual(tf.get_norm(), 1.2)

        tf = TimeFunction([T, Y], inter_mode=TimeFunction.InterLinear, dt=0.3)
        self.assertAlmostEqual(tf.get_norm(), 0)
Exemplo n.º 20
0
This example simulates a Hawkes process with a non constant, periodic baseline
"""
import numpy as np
import matplotlib.pyplot as plt

from tick.base import TimeFunction
from tick.hawkes import SimuHawkesExpKernels

from tick.plot import plot_point_process

period_length = 100
t_values = np.linspace(0, period_length)
y_values = 0.2 * np.maximum(np.sin(t_values *
                                   (2 * np.pi) / period_length), 0.2)
baselines = np.array(
    [TimeFunction((t_values, y_values), border_type=TimeFunction.Cyclic)])

decay = 0.1
adjacency = np.array([[0.5]])

hawkes = SimuHawkesExpKernels(adjacency,
                              decay,
                              baseline=baselines,
                              seed=2093,
                              verbose=False)
hawkes.track_intensity(0.1)
hawkes.end_time = 6 * period_length
hawkes.simulate()

fig, ax = plt.subplots(1, 1, figsize=(10, 4))
This example show how to simulate any inhomogeneous Poisson process. Its 
intensity is modeled through `tick.base.TimeFunction`
"""

import numpy as np
from tick.base import TimeFunction

from tick.plot import plot_point_process
from tick.simulation.inhomogeneous_poisson import SimuInhomogeneousPoisson

run_time = 30

T = np.arange((run_time * 0.9) * 5, dtype=float) / 5
Y = np.maximum(15 * np.sin(T) * (np.divide(np.ones_like(T),
                                           np.sqrt(T + 1) + 0.1 * T)), 0.001)

tf = TimeFunction((T, Y), dt=0.01)

# We define a 1 dimensional inhomogeneous Poisson process with the
# intensity function seen above
in_poi = SimuInhomogeneousPoisson([tf], end_time=run_time, verbose=False)

# We activate intensity tracking and launch simulation
in_poi.track_intensity(0.1)
in_poi.simulate()

# We plot the resulting inhomogeneous Poisson process with its
# intensity and its ticks over time
plot_point_process(in_poi)
Exemplo n.º 22
0
"""

import numpy as np
import matplotlib.pyplot as plt

from tick.inference import HawkesEM
from tick.simulation import SimuHawkes, HawkesKernelTimeFunc, HawkesKernelExp
from tick.base import TimeFunction
from tick.plot import plot_hawkes_kernels

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])

hawkes = SimuHawkes(baseline=baseline,
                    end_time=run_time,
                    verbose=False,
                    seed=2334)
Exemplo n.º 23
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)
Exemplo n.º 24
0
import matplotlib.pyplot as plt
import numpy as np
from tick.base import TimeFunction
from tick.plot import plot_timefunction

T = np.array([0, 3, 5.9, 8.001], dtype=float)
Y = np.array([2, 4.1, 1, 2], dtype=float)

tf_1 = TimeFunction((T, Y), dt=1.2)
tf_2 = TimeFunction((T, Y),
                    border_type=TimeFunction.BorderContinue,
                    inter_mode=TimeFunction.InterConstRight,
                    dt=0.01)
tf_3 = TimeFunction((T, Y),
                    border_type=TimeFunction.BorderConstant,
                    inter_mode=TimeFunction.InterConstLeft,
                    border_value=3)

time_functions = [tf_1, tf_2, tf_3]

_, ax_list = plt.subplots(1, 3, figsize=(14, 4), sharey=True)

for tf, ax in zip(time_functions, ax_list):
    plot_timefunction(tf_1, ax=ax)
    ax.set_ylim([-0.5, 6.0])
plt.show()
Exemplo n.º 25
0
def time_func(f, support, t0=0, steps=1000):
    t_values = np.linspace(0, support, steps + 1)
    y_values = f(t_values - t0) * np.heaviside(t_values - t0, 1)
    return TimeFunction(values=(t_values, y_values),
                        border_type=TimeFunction.Border0,
                        inter_mode=TimeFunction.InterLinear)
Exemplo n.º 26
0
 def setUp(self):
     size = 10
     self.y_values = np.random.rand(size)
     self.t_values = np.arange(size, dtype=float)
     self.time_function = TimeFunction([self.t_values, self.y_values])
     self.hawkes_kernel_time_func = HawkesKernelTimeFunc(self.time_function)