Skip to content

ENH: State space: Make initialization more flexible. - #4042

Closed
ChadFulton wants to merge 15 commits into
statsmodels:masterfrom
ChadFulton:ss-diffuse
Closed

ChadFulton wants to merge 15 commits into
statsmodels:masterfrom
ChadFulton:ss-diffuse

Conversation

@ChadFulton

Copy link
Copy Markdown
Member

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:

  • Known (set using known values)
  • Approximate diffuse (mean = 0, covariance a diagonal matrix with large diagonal elements)
  • Stationary (solve a discrete Lyapunov equation; this is currently done in Cython in the _{{prefix}}Statespace.initialize_stationary method)

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, SARIMAX models and UnobservedComponents models 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:

  1. The discrete Lyapunov equation and solution has to be set up in each model, even though it's really the same each time.
  2. It's slower to do this in Python space.

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 Initialization class for more details. This considerably simplifies initialization in SARIMAX and UnobservedComponents, 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.

@coveralls

coveralls commented Oct 19, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.08%) to 81.852% when pulling 2deecf6 on ChadFulton:ss-diffuse into 49cdbbd on statsmodels:master.

@jbrockmendel

Copy link
Copy Markdown
Contributor

I'll volunteer to review this, probably over the weekend.

@ChadFulton

Copy link
Copy Markdown
Member Author

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.

@ChadFulton

Copy link
Copy Markdown
Member Author

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.

@ChadFulton

Copy link
Copy Markdown
Member Author

@josef-pkt am I right in remembering that we are dropping support for scipy < 0.14 after 0.9?

@ChadFulton

Copy link
Copy Markdown
Member Author

Whoops, compatibility mode is required for scipy < 0.16. That throws a wrench in my plans.

@ChadFulton

Copy link
Copy Markdown
Member Author

@josef-pkt am I right in hoping that we are dropping support for scipy < 0.16 after 0.9?

@coveralls

coveralls commented Oct 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 81.847% when pulling 11fec1a on ChadFulton:ss-diffuse into 49cdbbd on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

@ChadFulton I have no problems with dropping scipy < 0.16.
Given our slower release cycle, we lag quite far behind in what versions we support. If there is a large enough benefit, then I think we should raise the minimum requirement faster than in the past. Even in Debian we seem to have more problems keeping up with changes in pandas, scipy and numpy rather than having problems with older versions of the dependencies.

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.)
Aside: changes in scipy.optimize affect mostly the user with problems or availability of optimizers depending on version. The latest scipy version usually works better but not always. For me it was maybe a loss of one or two days in getting unit tests to pass across all scipy versions on Travis in the recent count model optimization refactoring. Unfortunately, some fragility in fmin_bfgs is in recent versions of scipy that we cannot avoid yet with raising the minimum requirement, e.g. to >= 0.18))

@ChadFulton

Copy link
Copy Markdown
Member Author

@ChadFulton I have no problems with dropping scipy < 0.16.

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.

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

I usually don't have strong opinions on this either. I'm mostly on Py2.7 still :|

@josef-pkt

Copy link
Copy Markdown
Member

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
"""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does everything here need to be exposed externally?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I missed responding to this earlier, but I'm not sure what you mean by this - that the classes should be prefixed by underscores?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any particular reason you use 1 as the except val? IIUC -1 is standard.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think cdef void foo might achieve both goals.


np.import_array()

from statsmodels.src.math cimport *

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintenance would be much easier if imports were explicit instead of "cimport *".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flake8; please split up; easier to read;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea.


cdef int initialize_approximate_diffuse(self, int offset,
{{cython_type}} [::1, :] initial_stationary_state_cov) except 1:
cdef int i

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's very interesting, I hadn't seen that before. @bashtage could this be related to the seg faults on appveyor?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 @@
"""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this just a a non-cython implementation of _initialization.pyx?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No this is a wrapper. I'll explain more in the main comments.

@ChadFulton

ChadFulton commented Oct 22, 2017 •

Copy link
Copy Markdown
Member Author

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 Initialization class lets you describe the initialization for a group of states, and so every group has a corresponding Initialization object. If the group is initialized altogether, then the Initialization object would have a defined self.initialization_type. If the group contains n subgroups, then the Initialization object would contain n child Initialization objects. Eventually, the bottom level groups have defined self.initialization_type and do not contain children.

Each Initialization object has a corresponding _{{prefix}}Initialization Cython object, of the appropriate numeric type. The Cython objects actually do the work setting the block diagonal matrix elements. This work is requested by the initialize method of the _{{prefix}}Representation class, which iterates through all of the groups, subgroups, etc., and maintains an offset to figure out which diagonal block needs to be set for each group, this is used to give each block's _{{prefix}}Initialization object the correct location in memory.

@jbrockmendel

Copy link
Copy Markdown
Contributor

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.

@jbrockmendel

Copy link
Copy Markdown
Contributor

Should I hold off on reviewing until Travis errors are fixed?

@ChadFulton

Copy link
Copy Markdown
Member Author

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.

@ChadFulton

Copy link
Copy Markdown
Member Author

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.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was it determined that compatibility is going away soon?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this refers to the scipy version, then yes.
I think we should drop scipy < 0.16 right after the release of 0.9.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or we can even drop more if needed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The attributes being replaced are private. Is initialization intended to be used directly?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the current version of representation.pyx this is # I - T. Why the change?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bashtage

bashtage commented Nov 7, 2017

Copy link
Copy Markdown
Member

That's very interesting, I hadn't seen that before. @bashtage could this be related to the seg faults on appveyor?

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.

@ChadFulton

Copy link
Copy Markdown
Member Author

superseded by #4418

@ChadFulton ChadFulton closed this Jun 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants