示例#1
0
 def propagate(self, time0, value0, time, variate=None, state0=None, random_state=None):
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     if variate is None:
         if random_state is None: random_state = rnd.random_state()
         variate = random_state.normal(size=self.noise_dim)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     if isinstance(time_delta, np.timedelta64):
         time_delta = time_delta.item()
     if isinstance(time_delta, dt.timedelta):
         time_delta = time_delta.total_seconds() / self._time_unit.total_seconds()
     final_time_minus_time0 = self.__final_time - time0
     if isinstance(final_time_minus_time0, np.timedelta64):
         final_time_minus_time0 = final_time_minus_time0.item()
     if isinstance(final_time_minus_time0, dt.timedelta):
         final_time_minus_time0 = final_time_minus_time0.total_seconds() / self._time_unit.total_seconds()
     final_time_minus_time = self.__final_time - time
     if isinstance(final_time_minus_time, np.timedelta64):
         final_time_minus_time = time_delta.item()
     if isinstance(final_time_minus_time, dt.timedelta):
         final_time_minus_time = final_time_minus_time.total_seconds() / self._time_unit.total_seconds()
     mean = value0 + time_delta / final_time_minus_time0 * (self.__final_value - value0)
     cov_factor = time_delta * final_time_minus_time / final_time_minus_time0
     vol_factor = np.sqrt(cov_factor)
     vol = vol_factor * self.__vol
     return mean + np.dot(vol, variate)
示例#2
0
 def __init__(self, pct_drift=None, pct_vol=None, time_unit=dt.timedelta(days=1)):
     if pct_drift is None and pct_vol is None:
         pct_drift = 0.; pct_vol = 1.
     
     self._pct_drift, self._pct_vol = None, None
     
     if pct_drift is not None:
         self._pct_drift = npu.to_ndim_2(pct_drift, ndim_1_to_col=True, copy=True)
         process_dim = npu.nrow(self._pct_drift)
     if pct_vol is not None:
         self._pct_vol = npu.to_ndim_2(pct_vol, ndim_1_to_col=True, copy=True)
         process_dim = npu.nrow(self._pct_vol)
     
     if self._pct_drift is None: self._pct_drift = npu.col_of(process_dim, 0.)
     if self._pct_vol is None: self._pct_vol = np.eye(process_dim)
     
     npc.check_col(self._pct_drift)
     npc.check_nrow(self._pct_drift, process_dim)
     npc.check_nrow(self._pct_vol, process_dim)
     
     noise_dim = npu.ncol(self._pct_vol)
     self._pct_cov = stats.vol_to_cov(self._pct_vol)
     
     npu.make_immutable(self._pct_drift)
     npu.make_immutable(self._pct_vol)
     npu.make_immutable(self._pct_cov)
     
     self._to_string_helper_GeometricBrownianMotion = None
     self._str_GeometricBrownianMotion = None
     
     super(GeometricBrownianMotion, self).__init__(process_dim=process_dim, noise_dim=noise_dim,
             drift=lambda t, x: self._pct_drift * x,
             diffusion=lambda t, x: x * self._pct_vol,
             time_unit=time_unit)
示例#3
0
 def __next__(self):
     if self._time is None:
         self._time = next(self.__times)
     else:
         newtime = next(self.__times)
         time_delta = newtime - self._time
         if isinstance(time_delta, dt.timedelta):
             time_delta = time_delta.total_seconds(
             ) / self._time_unit.total_seconds()
         npu.col_of(self.__process.noise_dim, 0.)
         variate_delta = np.sqrt(time_delta) * npu.to_ndim_2(
             next(self.__variates), ndim_1_to_col=True, copy=False)
         drift = npu.to_ndim_2(self.__process.drift(self._time,
                                                    self.__value),
                               ndim_1_to_col=True,
                               copy=False)
         diffusion = npu.to_ndim_2(self.__process.diffusion(
             self._time, self.__value),
                                   ndim_1_to_col=True,
                                   copy=False)
         self.__value += drift * time_delta + diffusion.dot(variate_delta)
         self._time = newtime
     v = np.copy(self.__value)
     if self.__flatten: v = v.flatten()
     return self._time, v
示例#4
0
文件: processes.py 项目: zouhx11/tsa
    def __init__(self, mean=None, vol=None):
        if mean is None and vol is None:
            mean = 0.
            vol = 1.

        self._mean, self._vol = None, None

        if mean is not None:
            self._mean = npu.to_ndim_2(mean, ndim_1_to_col=True, copy=True)
            process_dim = npu.nrow(self._mean)
        if vol is not None:
            self._vol = npu.to_ndim_2(vol, ndim_1_to_col=True, copy=True)
            process_dim = npu.nrow(self._vol)

        if self._mean is None: self._mean = npu.col_of(process_dim, 0.)
        if self._vol is None: self._vol = np.eye(process_dim)

        npc.check_col(self._mean)
        npc.check_nrow(self._mean, process_dim)
        npc.check_nrow(self._vol, process_dim)

        noise_dim = npu.ncol(self._vol)
        self._cov = np.dot(self._vol, self._vol.T)

        npu.make_immutable(self._mean)
        npu.make_immutable(self._vol)
        npu.make_immutable(self._cov)

        self._to_string_helper_WienerProcess = None
        self._str_WienerProcess = None

        super(WienerProcess, self).__init__(process_dim=process_dim,
                                            noise_dim=noise_dim,
                                            drift=lambda t, x: self._mean,
                                            diffusion=lambda t, x: self._vol)
示例#5
0
 def propagate(self,
               time0,
               value0,
               time,
               variate=None,
               state0=None,
               random_state=None):
     if time == time0:
         return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     if variate is None:
         if random_state is None: random_state = rnd.random_state()
         variate = random_state.normal(size=self.noise_dim)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     if isinstance(time_delta, np.timedelta64):
         time_delta = time_delta.item()
     if isinstance(time_delta, dt.timedelta):
         time_delta = time_delta.total_seconds(
         ) / self._time_unit.total_seconds()
     mrf = self.mean_reversion_factor(time_delta)
     eye_minus_mrf = np.eye(self.process_dim) - mrf
     m = np.dot(mrf, value0) + np.dot(eye_minus_mrf, self._mean)
     c = self.noise_covariance(time_delta)
     return m + np.dot(np.linalg.cholesky(c), variate)
示例#6
0
文件: processes.py 项目: cav71/tsa
 def propagate(self, time, variate, time0, value0, state0=None):
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     return value0 * np.exp(
             (self._pct_drift - .5 * npu.col(*np.sum(self._pct_vol**2, axis=1))) * time_delta + \
             np.dot(self._pct_vol, np.sqrt(time_delta) * variate))
示例#7
0
文件: processes.py 项目: cav71/tsa
 def propagate(self, time, variate, time0, value0, state0=None):
     if self.noise_dim != self.process_dim:
         raise NotImplementedError('Cannot utilise the propagate_distr of the Markov process in propagate if noise_dim != process_dim; provide a custom implementation')
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     distr = self.propagate_distr(time, time0, distrs.DiracDelta.create(value0), assume_distr=True)
     return distr.mean + np.dot(np.linalg.cholesky(distr.cov), variate)
示例#8
0
    def __init__(self,
                 initial_value=None,
                 final_value=None,
                 initial_time=0.,
                 final_time=1.,
                 vol=None,
                 time_unit=dt.timedelta(days=1)):
        process_dim = 1

        self.__initial_value = None
        self.__final_value = None
        if initial_value is not None:
            self.__initial_value = npu.to_ndim_2(initial_value,
                                                 ndim_1_to_col=True,
                                                 copy=True)
            process_dim = npu.nrow(self.__initial_value)
        if final_value is not None:
            self.__final_value = npu.to_ndim_2(final_value,
                                               ndim_1_to_col=True,
                                               copy=True)
            process_dim = npu.nrow(self.__final_value)
        if self.__initial_value is None:
            self.__initial_value = npu.col_of(process_dim, 0.)
        if self.__final_value is None:
            self.__final_value = npu.col_of(process_dim, 0.)

        self.__vol = None
        if vol is not None:
            self.__vol = npu.to_ndim_2(vol, ndim_1_to_col=True, copy=True)
            process_dim = npu.nrow(self.__vol)
        if self.__vol is None: self.__vol = np.eye(process_dim)

        self.__initial_time = initial_time
        self.__final_time = final_time

        npc.check_col(self.__initial_value)
        npc.check_col(self.__final_value)
        npc.check_nrow(self.__initial_value, process_dim)
        npc.check_nrow(self.__final_value, process_dim)

        noise_dim = npu.ncol(self.__vol)
        self.__cov = stats.vol_to_cov(self.__vol)

        npu.make_immutable(self.__initial_value)
        npu.make_immutable(self.__final_value)
        npu.make_immutable(self.__vol)
        npu.make_immutable(self.__cov)

        self._to_string_helper_BrownianBridge = None
        self._str_BrownianBridge = None

        super(BrownianBridge,
              self).__init__(process_dim=process_dim,
                             noise_dim=noise_dim,
                             drift=lambda t, x: (self.__final_value - x) /
                             (self.__final_time - t),
                             diffusion=lambda t, x: self.__vol,
                             time_unit=time_unit)
示例#9
0
文件: processes.py 项目: valoox/tsa
    def __init__(self, transition=None, mean=None, vol=None):
        if transition is None and mean is None and vol is None:
            transition = 1.
            mean = 0.
            vol = 1.

        self._transition, self._mean, self._vol = None, None, None

        if transition is not None:
            self._transition = npu.to_ndim_2(transition,
                                             ndim_1_to_col=True,
                                             copy=True)
            process_dim = npu.nrow(self._transition)
        if mean is not None:
            self._mean = npu.to_ndim_2(mean, ndim_1_to_col=True, copy=True)
            process_dim = npu.nrow(self._mean)
        if vol is not None:
            self._vol = npu.to_ndim_2(vol, ndim_1_to_col=True, copy=True)
            process_dim = npu.nrow(self._vol)

        if self._transition is None: self._transition = np.eye(process_dim)
        if self._mean is None: self._mean = npu.col_of(process_dim, 0.)
        if self._vol is None: self._vol = np.eye(process_dim)

        npc.check_square(self._transition)
        npc.check_nrow(self._transition, process_dim)
        npc.check_col(self._mean)
        npc.check_nrow(self._mean, process_dim)
        npc.check_nrow(self._vol, process_dim)

        noise_dim = npu.ncol(self._vol)

        self._transition_x_2 = npu.kron_sum(self._transition, self._transition)
        self._transition_x_2_inverse = np.linalg.inv(self._transition_x_2)
        self._cov = np.dot(self._vol, self._vol.T)
        self._cov_vec = npu.vec(self._cov)

        self._cached_mean_reversion_factor = None
        self._cached_mean_reversion_factor_time_delta = None
        self._cached_mean_reversion_factor_squared = None
        self._cached_mean_reversion_factor_squared_time_delta = None

        npu.make_immutable(self._transition)
        npu.make_immutable(self._transition_x_2)
        npu.make_immutable(self._transition_x_2_inverse)
        npu.make_immutable(self._mean)
        npu.make_immutable(self._vol)
        npu.make_immutable(self._cov)
        npu.make_immutable(self._cov_vec)

        self._to_string_helper_OrnsteinUhlenbeckProcess = None
        self._str_OrnsteinUhlenbeckProcess = None

        super(OrnsteinUhlenbeckProcess, self).__init__(
            process_dim=process_dim,
            noise_dim=noise_dim,
            drift=lambda t, x: -np.dot(self._transition, x - self._mean),
            diffusion=lambda t, x: self._vol)
示例#10
0
    def __init__(self,
                 particles=None,
                 weights=None,
                 dim=None,
                 use_n_minus_1_stats=False,
                 sampler=None,
                 copy=True):
        self._particles, self._weights, self._dim = None, None, None

        if particles is not None:
            self._particles = npu.to_ndim_2(particles,
                                            ndim_1_to_col=True,
                                            copy=copy)
            self._dim = npu.ncol(self._particles)
            if weights is None:
                weights = np.ones((npu.nrow(self._particles), 1))
                weights /= float(npu.nrow(self._particles))

        if weights is not None:
            checks.check_not_none(particles)
            self._weights = npu.to_ndim_2(weights,
                                          ndim_1_to_col=True,
                                          copy=copy)
            self._dim = npu.ncol(self._particles)

        if dim is not None:
            self._dim = dim

        if self._particles is not None:
            npc.check_ncol(self._particles, self._dim)
        if self._weights is not None:
            npc.check_nrow(self._weights, npu.nrow(self._particles))

        npu.make_immutable(self._particles, allow_none=True)
        npu.make_immutable(self._weights, allow_none=True)

        self._use_n_minus_1_stats = use_n_minus_1_stats

        # "n minus 1" (unbiased) stats only make sense when using "repeat"-type weights, meaning that each weight
        # represents the number of occurrences of one observation.
        #
        # See https://stats.stackexchange.com/questions/61225/correct-equation-for-weighted-unbiased-sample-covariance

        self._effective_particle_count = None
        self._weight_sum = None
        self._mean = None
        self._var_n = None
        self._var_n_minus_1 = None
        self._cov_n = None
        self._cov_n_minus_1 = None
        self._vol_n = None
        self._vol_n_minus_1 = None

        self._to_string_helper_EmpiricalDistr = None
        self._str_EmpiricalDistr = None

        super().__init__(do_not_init=True)
示例#11
0
文件: processes.py 项目: zouhx11/tsa
 def propagate(self, time, variate, time0, value0, state0=None):
     if time == time0:
         return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     return value0 + self._mean * time_delta + np.dot(
         self._vol,
         np.sqrt(time_delta) * variate)
示例#12
0
    def test_to_ndim_2(self):
        for v in [ 429., [429.], [[429.]], np.array(429.), np.array([429.]), np.array([[429.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (1, 1))
            npt.assert_almost_equal(r, np.array([[429.]]))
        
        for v in [ [429., 5.], [[429., 5.]], np.array([429., 5.]), np.array([[429., 5.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (1, 2))
            npt.assert_almost_equal(r, np.array([[429., 5.]]))
        
        for v in [ [[429.], [5.]], np.array([[429.], [5.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (2, 1))
            npt.assert_almost_equal(r, np.array([[429.], [5.]]))
        
        for v in [ [429., 5., 2., 14.], [[429., 5., 2., 14.]], np.array([429., 5., 2., 14.]), np.array([[429., 5., 2., 14.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (1, 4))
            npt.assert_almost_equal(r, np.array([[429., 5., 2., 14.]]))
        
        for v in [ [[429., 5.], [2., 14.]], np.array([[429., 5.], [2., 14.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (2, 2))
            npt.assert_almost_equal(r, np.array([[429., 5.], [2., 14.]]))
        
        for v in [ [[429.], [5.], [2.], [14.]], np.array([[429.], [5.], [2.], [14.]]) ]:
            r = npu.to_ndim_2(v)
            self.assertTrue(checks.is_numpy_array(r))
            self.assertEqual(np.shape(r), (4, 1))
            npt.assert_almost_equal(r, np.array([[429.], [5.], [2.], [14.]]))
        
        npt.assert_equal(npu.to_ndim_2(None), np.array([[None]]))
        
        a = np.array([[429., 5.], [2., 14.]])
        b = npu.to_ndim_2(a, copy=False)
        b[1, 1] = 42.
        npt.assert_almost_equal(b, np.array([[429., 5.], [2., 42.]]))
        npt.assert_almost_equal(a, np.array([[429., 5.], [2., 42.]]))
    
        a = [[429., 5.], [2., 14.]]
        b = npu.to_ndim_2(a, copy=False)
        b[1, 1] = 42.
        npt.assert_almost_equal(b, np.array([[429., 5.], [2., 42.]]))
        npt.assert_almost_equal(a, np.array([[429., 5.], [2., 14.]]))

        a = np.array([[429., 5.], [2., 14.]])
        b = npu.to_ndim_2(a, copy=True)
        b[1, 1] = 42.
        npt.assert_almost_equal(b, np.array([[429., 5.], [2., 42.]]))
        npt.assert_almost_equal(a, np.array([[429., 5.], [2., 14.]]))
示例#13
0
文件: processes.py 项目: cav71/tsa
 def propagate(self, time, variate, time0, value0, state0=None):
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     mrf = self.mean_reversion_factor(time_delta)
     eye_minus_mrf = np.eye(self.process_dim) - mrf
     m = np.dot(mrf, value0) + np.dot(eye_minus_mrf, self._mean)
     c = self.noise_covariance(time_delta)
     return m + np.dot(np.linalg.cholesky(c), variate)
示例#14
0
文件: processes.py 项目: cav71/tsa
 def propagate(self, time, variate, time0, value0, state0=None):
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     mean = value0 + time_delta / (self.__final_time - time0) * (self.__final_value - value0)
     cov_factor = (time - time0) * (self.__final_time - time) / (self.__final_time - time0)
     vol_factor = np.sqrt(cov_factor)
     vol = vol_factor * self.__vol
     return mean + np.dot(vol, variate)
示例#15
0
 def propagate(self, time0, value0, time, variate=None, state0=None, random_state=None):
     if time == time0: return npu.to_ndim_2(value0, ndim_1_to_col=True, copy=True)
     value0 = npu.to_ndim_2(value0, ndim_1_to_col=True, copy=False)
     if variate is None:
         if random_state is None: random_state = rnd.random_state()
         variate = random_state.normal(size=self.noise_dim)
     variate = npu.to_ndim_2(variate, ndim_1_to_col=True, copy=False)
     time_delta = time - time0
     if isinstance(time_delta, np.timedelta64):
         time_delta = time_delta.item()
     if isinstance(time_delta, dt.timedelta):
         time_delta = time_delta.total_seconds() / self._time_unit.total_seconds()
     return value0 + self._mean * time_delta + np.dot(self._vol, np.sqrt(time_delta) * variate)
示例#16
0
    def __init__(self, mean_of_log=None, cov_of_log=None, vol_of_log=None, dim=None, copy=True):
        if mean_of_log is not None and dim is not None and np.size(mean_of_log) == 1:
            mean_of_log = npu.col_of(dim, npu.to_scalar(mean_of_log))
        
        if mean_of_log is None and vol_of_log is None and cov_of_log is None:
            self._dim = 1 if dim is None else dim
            mean_of_log = npu.col_of(self._dim, 0.)
            cov_of_log = np.eye(self._dim)
            vol_of_log = np.eye(self._dim)
            
        self._dim, self._mean_of_log, self._vol_of_log, self._cov_of_log = None, None, None, None
        
        # TODO We don't currently check whether cov_of_log and vol_of_log are consistent, i.e. that cov_of_log = np.dot(vol_of_log, vol_of_log.T) -- should we?
        
        if mean_of_log is not None:
            self._mean_of_log = npu.to_ndim_2(mean_of_log, ndim_1_to_col=True, copy=copy)
            self._dim = npu.nrow(self._mean_of_log)
        if cov_of_log is not None:
            self._cov_of_log = npu.to_ndim_2(cov_of_log, ndim_1_to_col=True, copy=copy)
            self._dim = npu.nrow(self._cov_of_log)
        if vol_of_log is not None:
            self._vol_of_log = npu.to_ndim_2(vol_of_log, ndim_1_to_col=True, copy=copy)
            self._dim = npu.nrow(self._vol_of_log)
        
        if self._mean_of_log is None: self._mean_of_log = npu.col_of(self._dim, 0.)
        if self._cov_of_log is None and self._vol_of_log is None:
            self._cov_of_log = np.eye(self._dim)
            self._vol_of_log = np.eye(self._dim)
        npc.check_col(self._mean_of_log)
        npc.check_nrow(self._mean_of_log, self._dim)
        if self._cov_of_log is not None:
            npc.check_nrow(self._cov_of_log, self._dim)
            npc.check_square(self._cov_of_log)
        if self._vol_of_log is not None:
            npc.check_nrow(self._vol_of_log, self._dim)

        if self._cov_of_log is None: self._cov_of_log = stats.vol_to_cov(self._vol_of_log)
        if self._vol_of_log is None: self._vol_of_log = stats.cov_to_vol(self._cov_of_log)
            
        npu.make_immutable(self._mean_of_log)
        npu.make_immutable(self._cov_of_log)
        npu.make_immutable(self._vol_of_log)

        mean = np.exp(self._mean_of_log + .5 * npu.col(*[self._cov_of_log[i,i] for i in range(self._dim)]))
        cov = np.array([[np.exp(self._mean_of_log[i,0] + self._mean_of_log[j,0] + .5 * (self._cov_of_log[i,i] + self._cov_of_log[j,j])) * (np.exp(self._cov_of_log[i,j]) - 1.) for j in range(self._dim)] for i in range(self._dim)])
        vol = stats.cov_to_vol(cov)
        
        self._to_string_helper_LogNormalDistr = None
        self._str_LogNormalDistr = None
        
        super().__init__(mean, cov, vol, self._dim, copy)
示例#17
0
    def __init__(self,
                 mean=None,
                 cov=None,
                 vol=None,
                 dim=None,
                 copy=True,
                 do_not_init=False):
        if not do_not_init:
            if mean is not None and dim is not None and np.size(mean) == 1:
                mean = npu.col_of(dim, npu.to_scalar(mean))

            if mean is None and vol is None and cov is None:
                self._dim = 1 if dim is None else dim
                mean = npu.col_of(self._dim, 0.)
                cov = np.eye(self._dim)
                vol = np.eye(self._dim)

            self._dim, self._mean, self._vol, self._cov = None, None, None, None

            # TODO We don't currently check whether cov and vol are consistent, i.e. that cov = np.dot(vol, vol.T) -- should we?

            if mean is not None:
                self._mean = npu.to_ndim_2(mean, ndim_1_to_col=True, copy=copy)
                self._dim = npu.nrow(self._mean)
            if cov is not None:
                self._cov = npu.to_ndim_2(cov, ndim_1_to_col=True, copy=copy)
                self._dim = npu.nrow(self._cov)
            if vol is not None:
                self._vol = npu.to_ndim_2(vol, ndim_1_to_col=True, copy=copy)
                self._dim = npu.nrow(self._vol)

            if self._mean is None: self._mean = npu.col_of(self._dim, 0.)
            if self._cov is None and self._vol is None:
                self._cov = np.eye(self._dim)
                self._vol = np.eye(self._dim)
            npc.check_col(self._mean)
            npc.check_nrow(self._mean, self._dim)
            if self._cov is not None:
                npc.check_nrow(self._cov, self._dim)
                npc.check_square(self._cov)
            if self._vol is not None:
                npc.check_nrow(self._vol, self._dim)

            npu.make_immutable(self._mean)
            if self._cov is not None: npu.make_immutable(self._cov)
            if self._vol is not None: npu.make_immutable(self._vol)

        self._to_string_helper_WideSenseDistr = None
        self._str_WideSenseDistr = None

        super().__init__()
示例#18
0
 def observe(self, obs, time=None, true_value=None, predicted_obs=None):
     time, obs_distr = filtering._time_and_obs_distr(
         obs, time, self.filter.time)
     if true_value is not None: true_value = npu.to_ndim_2(true_value)
     if predicted_obs is None:
         predicted_obs = self.predict(time, true_value)
     return self.filter.observe(obs_distr, predicted_obs, true_value)
示例#19
0
 def __init__(self, obs_matrix):
     super().__init__()
     if not checks.is_numpy_array(obs_matrix) and not checks.is_iterable(obs_matrix):
         obs_matrix = (obs_matrix,)
     self._obs_matrix = npu.make_immutable(
             block_diag(
                     *[npu.to_ndim_2(om, ndim_1_to_col=False, copy=False) for om in obs_matrix]))
     self._to_string_helper_KalmanFilterObsModel = None
     self._str_KalmanFilterObsModel = None
示例#20
0
文件: simulation.py 项目: cav71/tsa
 def __init__(self, process, initial_value=None, times=None, variates=None, time_unit=dt.timedelta(days=1), flatten=False):
     checks.check_instance(process, proc.ItoProcess)
     self.__process = process
     self.__value = npu.to_ndim_2(initial_value, ndim_1_to_col=True, copy=True) if initial_value is not None else npu.col_of(process.process_dim, 0.)
     self.__times = iter(times) if times is not None else xtimes(0., None, 1.)
     self.__variates = variates if variates is not None else rnd.multivatiate_normals(ndim=process.noise_dim)
     self._time = None
     self._time_unit = time_unit
     self.__flatten = flatten
示例#21
0
 def mean(self):
     if self._mean is None:
         self._mean = np.average(self._particles,
                                 weights=self._weights.flat,
                                 axis=0)
         self._mean = npu.to_ndim_2(self._mean,
                                    ndim_1_to_col=True,
                                    copy=False)
         npu.make_immutable(self._mean)
     return self._mean
示例#22
0
 def var_n(self):
     if self._var_n is None:
         self._var_n = np.average((self._particles - self.mean.T)**2,
                                  weights=self._weights.flat,
                                  axis=0)
         self._var_n = npu.to_ndim_2(self._var_n,
                                     ndim_1_to_col=True,
                                     copy=False)
         npu.make_immutable(self._var_n)
     return self._var_n
示例#23
0
 def create_multiscale_from_vol(transition_vector, mean, vol):
     transition_vector = npu.to_ndim_2(transition_vector, ndim_1_to_col=True, copy=False)
     npc.check_col(transition_vector)
     process_dim = np.size(transition_vector)
     transition = np.zeros((process_dim, process_dim))
     checks.check_some_number(mean)
     mean_vector = np.zeros((process_dim, 1))
     mean_vector[0, 0] = mean
     mean_vector[1, 0] = mean
     for i in range(process_dim):
         transition[(i, i)] = transition_vector[i]
         if i < process_dim - 1: transition[(i+1, i)] = -transition_vector[i+1]
     return OrnsteinUhlenbeckProcess(transition, mean_vector, vol)
示例#24
0
文件: stats.py 项目: valoox/tsa
def cor_to_cov(cors, vars=None, sds=None, copy=True):  # @ReservedAssignment
    assert (vars is None and sds is not None) or (vars is not None and sds is None)
    sds = np.sqrt(vars) if vars is not None else sds
    if isinstance(cors, (utils.DiagonalArray, utils.SubdiagonalArray)):
        cors = cors.tonumpyarray()
    cors = npu.to_ndim_2(cors, copy=copy)
    dim = len(vars)
    assert dim == np.shape(cors)[0] and dim == np.shape(cors)[1]
    np.fill_diagonal(cors, 1.)
    for i in range(dim):
        cors[i,:] = sds[i] * cors[i,:]
        cors[:,i] = sds[i] * cors[:,i]
    npu.lower_to_symmetric(cors, copy=False)
    return cors
示例#25
0
文件: kde.py 项目: vishalbelsare/tsa
    def pdf(self, points):
        """
        Evaluate the estimated pdf on a set of points.

        Parameters
        ----------
        points : (# of dimensions, # of points)-array
            Alternatively, a (# of dimensions,) vector can be passed in and treated as a single point.

        Returns
        -------
        values : (# of points,)-array
            The values at each point.

        Raises
        ------
        ValueError : if the dimensionality of the input points is different than the dimensionality of the KDE.
        """
        points = npu.to_ndim_2(points, ndim_1_to_col=True)

        m, d = np.shape(points)
        if d != self.dim:
            if d == 1 and m == self.dim:
                # points was passed in as a column vector
                points = np.reshape(points, (1, self.dim))
                m = 1
            else:
                msg = "points have dimension %s, particles has dimension %s" % (
                    d, self.dim)
                raise ValueError(msg)

        # compute the normalized residuals
        chi2 = cdist(points,
                     self.empirical_distr.particles,
                     'mahalanobis',
                     VI=self.inv_cov)**2
        # compute the pdf
        result = np.sum(
            np.exp(-.5 * chi2) * self.empirical_distr.normalized_weights.T,
            axis=1) / self.pdf_norm_factor

        return result
示例#26
0
def multivariate_normal(mean=None,
                        cov=None,
                        size=None,
                        ndim=None,
                        random_state=None):
    global _rs
    if ndim is None:
        if mean is not None: ndim = np.size(mean)
        elif cov is not None: ndim = npu.nrow(cov)
        else: ndim = 1
    if ndim is not None:
        if mean is None: mean = npu.ndim_1_of(ndim, 0.)
        if cov is None: cov = np.eye(ndim, ndim)
    mean = npu.to_ndim_1(mean)
    cov = npu.to_ndim_2(cov)
    npc.check_size(mean, ndim)
    npc.check_nrow(cov, ndim)
    npc.check_square(cov)
    if random_state is None: random_state = _rs()
    return random_state.multivariate_normal(mean, cov, size)
示例#27
0
def multivariate_lognormal(mean_of_log=0.,
                           cov_of_log=1.,
                           size=None,
                           ndim=None,
                           random_state=None):
    global _rs
    if ndim is None:
        if mean_of_log is not None: ndim = np.size(mean_of_log)
        elif cov_of_log is not None: ndim = npu.nrow(cov_of_log)
        else: ndim = 1
    if ndim is not None:
        if mean_of_log is None: mean_of_log = npu.ndim_1_of(ndim, 0.)
        if cov_of_log is None: cov_of_log = np.eye(ndim, ndim)
    mean_of_log = npu.to_ndim_1(mean_of_log)
    cov_of_log = npu.to_ndim_2(cov_of_log)
    npc.check_size(mean_of_log, ndim)
    npc.check_nrow(cov_of_log, ndim)
    npc.check_square(cov_of_log)
    if random_state is None: random_state = _rs()
    normal = random_state.multivariate_normal(mean_of_log, cov_of_log, size)
    return np.exp(normal)
示例#28
0
    def __init__(self, mean=None, dim=None, copy=True):
        if mean is not None and dim is not None and np.size(mean) == 1:
            mean = npu.col_of(dim, npu.to_scalar(mean))

        if mean is None:
            dim = 1 if dim is None else dim
            mean = npu.col_of(dim, 0.)

        self._mean = npu.to_ndim_2(mean, ndim_1_to_col=True, copy=copy)
        if dim is None: dim = npu.nrow(self._mean)
        self._dim = dim

        npc.check_col(self._mean)
        npc.check_nrow(self._mean, self._dim)

        npu.make_immutable(self._mean)

        self._zero_cov = None

        self._to_string_helper_DiracDeltaDistr = None
        self._str_DiracDeltaDistr = None
示例#29
0
 def particle(self, idx):
     if self.particle_count == 0:
         raise IndexError('The empirical distribution has no particles')
     return npu.to_ndim_2(self._particles[idx, :],
                          ndim_1_to_col=True,
                          copy=False)
示例#30
0
文件: stats.py 项目: zouhx11/tsa
def cov_to_vol(cov):
    cov = npu.to_ndim_2(cov, ndim_1_to_col=True, copy=False)
    return np.linalg.cholesky(cov)