Skip to content

Commit d16370c

Browse files
committed
AR RV
1 parent ced3de9 commit d16370c

File tree

1 file changed

+37
-42
lines changed

1 file changed

+37
-42
lines changed

pymc/distributions/timeseries.py

Lines changed: 37 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
from pymc.distributions.continuous import Flat, Normal, get_tau_sigma
2323
from pymc.distributions.shape_utils import to_tuple
2424

25+
from aesara.tensor.random.op import RandomVariable
26+
from pymc.aesaraf import floatX, intX
27+
from aesara.tensor.var import TensorVariable
28+
from typing import Tuple
29+
2530
__all__ = [
2631
"AR1",
2732
"AR",
@@ -33,49 +38,39 @@
3338
]
3439

3540

36-
class AR1(distribution.Continuous):
37-
"""
38-
Autoregressive process with 1 lag.
39-
40-
Parameters
41-
----------
42-
k: tensor
43-
effect of lagged value on current value
44-
tau_e: tensor
45-
precision for innovations
46-
"""
47-
48-
def __init__(self, k, tau_e, *args, **kwargs):
49-
super().__init__(*args, **kwargs)
50-
self.k = k = at.as_tensor_variable(k)
51-
self.tau_e = tau_e = at.as_tensor_variable(tau_e)
52-
self.tau = tau_e * (1 - k ** 2)
53-
self.mode = at.as_tensor_variable(0.0)
54-
55-
def logp(self, x):
56-
"""
57-
Calculate log-probability of AR1 distribution at specified value.
58-
59-
Parameters
60-
----------
61-
x: numeric
62-
Value for which log-probability is calculated.
63-
64-
Returns
65-
-------
66-
TensorVariable
67-
"""
68-
k = self.k
69-
tau_e = self.tau_e # innovation precision
70-
tau = tau_e * (1 - k ** 2) # ar1 precision
71-
72-
x_im1 = x[:-1]
73-
x_i = x[1:]
74-
boundary = Normal.dist(0.0, tau=tau).logp
75-
76-
innov_like = Normal.dist(k * x_im1, tau=tau_e).logp(x_i)
77-
return boundary(x[0]) + at.sum(innov_like)
41+
class ARrv(RandomVariable):
42+
name = "AR"
43+
ndim_supp = 0
44+
ndims_params = [0, 0, 0, 0, 0]
45+
dtype = "floatX"
46+
_print_name = ("AR", "\\operatorname{AR}")
47+
48+
49+
def __call__(self, phi, init=0.0, mu=0.0, sigma=1.0, **kwargs) -> TensorVariable:
50+
return super().__call__(phi, init, mu, sigma, **kwargs)
51+
52+
53+
@classmethod
54+
def rng_fn(
55+
cls,
56+
rng: np.random.default_rng(),
57+
phi: float,
58+
init: float,
59+
mu: np.ndarray,
60+
sigma: np.ndarray,
61+
size: Tuple[int, ...],
62+
) -> np.ndarray:
63+
64+
phi = np.asarray(phi)
65+
if init!=0.0:
66+
y = np.asarray([init])
67+
else:
68+
y = rng.normal(0.0, 1.0,size=1)
7869

70+
for i in range(1, size[0]):
71+
y = np.append(y, mu + phi*y[-1] + rng.normal(0.0, sigma))
72+
73+
return y
7974

8075
class AR(distribution.Continuous):
8176
r"""

0 commit comments

Comments
 (0)