Repository navigation
ENH: State space: Make initialization more flexible. - #4042
ChadFulton wants to merge 15 commits into
Conversation
|
I'll volunteer to review this, probably over the weekend. |
|
Thanks! Also, the test failures are because I forgot to set the code so that it only uses the new initialization when "compatibility mode" (i.e. old scipy) is not on, other than that I believe it's good to go. |
|
After thinking about this, I think we should wait to merge this until after 0.9 for this PR when I believe we can drop the compatibility mode, so I will remove the last commit. |
|
@josef-pkt am I right in remembering that we are dropping support for scipy < 0.14 after 0.9? |
|
Whoops, compatibility mode is required for scipy < 0.16. That throws a wrench in my plans. |
|
@josef-pkt am I right in hoping that we are dropping support for scipy < 0.16 after 0.9? |
|
@ChadFulton I have no problems with dropping scipy < 0.16. However, I don't see a strong reason to raise minimum versions fast if there is essentially no benefit for us. (E.g. personally I update my python environment maybe every two years, or on average once a year if I have computer problems.) |
That would be great from my perspective! To be fair, this PR is not essential in any way, so we don't have to push it if there are competing reasons not to.
I usually don't have strong opinions on this either. I'm mostly on Py2.7 still :| |
11fec1a to
2deecf6
Compare
|
The main advantage of dropping older scipy version is that you can get rid of the compatibility part in statespace which should make your maintenance and development easier, independent of specific PRs. |
| #cython: boundscheck=False | ||
| #cython: wraparound=False | ||
| #cython: cdivision=False | ||
| """ |
There was a problem hiding this comment.
Does everything here need to be exposed externally?
There was a problem hiding this comment.
I missed responding to this earlier, but I'm not sure what you mean by this - that the classes should be prefixed by underscores?
There was a problem hiding this comment.
One of the purposes of the pxd file is to make it expose things to be cimported. (The other big one is for type declarations, but since you already have those in the pyx file that is unnecessary). So anything that is not needed outside of statespace._intialization can be excluded from the pxd file.
The main benefit of this is for the reviewer: if it is easy to check that a function/class is only used internally, it becomes much easier to track reason about its use cases.
| cdef int initialize_diffuse(self, int offset, np.float32_t [::1, :] initial_diffuse_state_cov) except 1 | ||
| cdef int initialize_approximate_diffuse(self, int offset, np.float32_t [::1, :] initial_stationary_state_cov) except 1 | ||
| cdef int initialize_stationary_constant(self, int offset, sStatespace model, np.float32_t [:] initial_state_mean, int complex_step=*) except 1 | ||
| cdef int initialize_stationary_stationary_cov(self, int offset, sStatespace model, np.float32_t [::1, :] initial_stationary_state_cov, int complex_step=*) except 1 |
There was a problem hiding this comment.
Any particular reason you use 1 as the except val? IIUC -1 is standard.
There was a problem hiding this comment.
No reason, simply that exceptions require a return value. I guess the Cython docs have except -1, but since the other SS code has return 1 I suppose that we can keep it as is?
There was a problem hiding this comment.
It looks like most of these are returning 0 unconditionally. Getting rid of the return value/declaration would obviate the need to have the except 1 clause at all. The -1 seems to be a default elsewhere (namely pandas), but this is definitely not a big deal.
There was a problem hiding this comment.
Yes, that's definitely doable. I guess I vaguely thought maybe returning a fixed C value would be faster than the default (which is I guess a Python None object, maybe?), but I have no real reason to believe that.
There was a problem hiding this comment.
I think cdef void foo might achieve both goals.
|
|
||
| np.import_array() | ||
|
|
||
| from statsmodels.src.math cimport * |
There was a problem hiding this comment.
Maintenance would be much easier if imports were explicit instead of "cimport *".
There was a problem hiding this comment.
Good point, this file doesn't need these imports.
| # Internal temporary matrices | ||
| dim2[0] = self.k_states; dim2[1] = self.k_states; | ||
| self._tmp_transition = np.PyArray_ZEROS(2, dim2, {{typenum}}, FORTRAN) | ||
| dim2[0] = self.k_states; dim2[1] = self.k_states; |
There was a problem hiding this comment.
flake8; please split up; easier to read;
|
|
||
| cdef int initialize_approximate_diffuse(self, int offset, | ||
| {{cython_type}} [::1, :] initial_stationary_state_cov) except 1: | ||
| cdef int i |
There was a problem hiding this comment.
My understanding is that Py_ssize_t is preferred to int for this. You can get away without importing it explicitly or from cython cimport Py_ssize_t.
There was a problem hiding this comment.
That's very interesting, I hadn't seen that before. @bashtage could this be related to the seg faults on appveyor?
There was a problem hiding this comment.
I'd be surprised. AFAIK Py_ssize_t is basically an unsigned int. But its the suggested usage for scalar indexing.
| @@ -0,0 +1,607 @@ | |||
| """ | |||
There was a problem hiding this comment.
Is this just a a non-cython implementation of _initialization.pyx?
There was a problem hiding this comment.
No this is a wrapper. I'll explain more in the main comments.
|
The main idea here is that if your state space model has separate groups of states, then your initial state covariance matrix will likely be block diagonal. Since the groups of states are unrelated, their initializations may be different. For example, in an ARMAX model in which the regression coefficients are part of the state vector, the regression coefficients are given a diffuse initialization whereas the ARMA process is given a stationary initialization. The basic idea in the code is that any group of states can either be initialized all together or can be broken up into subgroups. Starting with the entire set of states, one could initialize it altogether (e.g. an ARMA model would just be initialized as stationary) or one could set up a few groups (e.g. the ARMAX model would have a diffuse group and a stationary group). Then, each of those groups could be initialized altogether, or they could be set up to themselves contain subgroups, and so forth. The Each |
|
Makes sense. Style comments aside, this looks good on a first pass. I'll look over the non-cython file and do a second pass in the next couple days. |
|
Should I hold off on reviewing until Travis errors are fixed? |
Travis errors won't be fixed, since they are all (I think) from scipy < 0.16 where this explicitly fails. |
By the way, I definitely agree with this. Looking forward to getting rid of that code! |
| @@ -56,10 +57,16 @@ def set_mode(compatibility=None): | |||
| # Initialize the appropriate mode | |||
| if not compatibility: | |||
There was a problem hiding this comment.
was it determined that compatibility is going away soon?
There was a problem hiding this comment.
If this refers to the scipy version, then yes.
I think we should drop scipy < 0.16 right after the release of 0.9.
There was a problem hiding this comment.
or we can even drop more if needed.
There was a problem hiding this comment.
Good point, this section needs to be written, but maybe I'll delay that until after a PR that drops compatibility mode in master, after 0.9.
I believe 0.16 is all we need for state space, but going higher certainly wouldn't hurt anything from my perspective!
There was a problem hiding this comment.
Should I hold off on further review until some upcoming set of edits?
| assert_equal(mod._initial_state.sum(), 3) | ||
| assert_equal(mod._initial_state_cov.diagonal().sum(), 6) | ||
| assert_equal(mod.initialization.constant.sum(), 3) | ||
| assert_equal(mod.initialization.stationary_cov.diagonal().sum(), 6) |
There was a problem hiding this comment.
The attributes being replaced are private. Is initialization intended to be used directly?
There was a problem hiding this comment.
Yes, these may be created and manipulated by end-users, even separate from model classes (e.g. in principle someone might want to construct their own initialization even for an SARIMAX class, if e.g. they had some kind of prior).
| dim2[1] = self.k_states | ||
| ipiv = np.PyArray_ZEROS(2, dim2, np.NPY_INT32, FORTRAN) | ||
|
|
||
| # Create T - I |
There was a problem hiding this comment.
In the current version of representation.pyx this is # I - T. Why the change?
There was a problem hiding this comment.
I guess it's just easier to do using the BLAS calls that I know (of course I'm not ruling out that there may be a better way to do it altogether): subtracting 1 from the diagonal elements and then scaling the whole thing by -1 is faster than constructing an identity matrix and subtracting the T matrix from it.
Unlikely I caught one locally with a debug build. The segfault is a 0xc5 where something is trying to read self.nobs after self has been garbage collected. Very strange. |
|
superseded by #4418 |
Initializing the Kalman filter involves determining the distribution of the initial state vector, i.e. setting its mean and covariance matrices.
Currently, users are presented with three options:
_{{prefix}}Statespace.initialize_stationarymethod)Each of these sets the full mean and covariance matrix for the initial state vector. However, this can be inconvenient in models where e.g. some elements are stationary and some elements are non-stationary (for example,
SARIMAXmodels andUnobservedComponentsmodels often have this feature).In practice, this has meant that if there are both types of states, the "Known" option has to be used, and the stationary component has to be computed manually (see e.g.
SARIMAX.initialize_state). This is less than ideal for at least two reasons:In this PR, I add the ability to specify initialization separately for separate (consecutive) blocks of the state vector, and convert all existing classes to use the new initialization system. See the docstring of the
Initializationclass for more details. This considerably simplifies initialization inSARIMAXandUnobservedComponents, and should improve performance somewhat.The other major benefit of this PR is that it is one of the steps necessary to get exact diffuse initialization working.
Of course the downside is another Cython class and somehow I've managed to add 1600 lines.