Skip to content

ENH: Fast ARMA innovation algorithm and loglike computation - #5360

Merged
ChadFulton merged 3 commits into
statsmodels:masterfrom
ChadFulton:innov_arma
Dec 27, 2018
Merged

ChadFulton merged 3 commits into
statsmodels:masterfrom
ChadFulton:innov_arma

Conversation

@ChadFulton

Copy link
Copy Markdown
Member

This adds a fast Cython innovations algorithm specific to ARMA processes along with a fast exact loglikelihood computation method. (this isn't exactly #5326, since this is only for ARMA processes)

In most cases, it is just about as fast as the state space models, but it scales to large AR and MA orders much better because we can exploit a lot of zeros that appear in the innovations algorithm once we make the transformation suggested by Brockwell and Davis (section 3.3).

For example, it should make it feasible to estimate the parameters of an ARMA model with 50000 observations and a seasonal periods of a year, which would be extremely slow when using the state space models.

It's not a full model class right now, of course, but I think the plan would be to eventually embed it as an alternative fit method in SARIMAX.

And of course all of the details are still up in the air: where to put it, what to call it, etc...

@ChadFulton ChadFulton added this to the 0.11 milestone Nov 2, 2018
@jbrockmendel

Copy link
Copy Markdown
Contributor

@ChadFulton I'll give this a look over the weekend. Not just as a thank-you for handling obvious fixes elsewhere, but it helps.

@ChadFulton

Copy link
Copy Markdown
Member Author

Thanks!

FYI some functions in the _arma_innovations.pyx.in file have two versions, one with the suffix _fast and one without it. There's more detailed documentation in the file, but basically the ones without _fast show the basic theoretical process more clearly, while the _fast versions are the ones that use a couple of tricks to avoid allocating huge arrays and performing useless loops.

I sort of assume that we'll drop the slower versions before merging (maybe keeping them in Git history for reference though), since they have no advantage.

@coveralls

coveralls commented Nov 2, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 84.284% when pulling b4678b8 on ChadFulton:innov_arma into 5b12177 on statsmodels:master.

import numpy as np
import warnings
from statsmodels.tsa import arima_process
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.

can you make these explicit. tracking down what is actually imported/used can be a PITA.

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

import warnings
from statsmodels.tsa import arima_process
from statsmodels.src.math cimport *
cimport numpy as np

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.

Can you make this cimport numpy as cnp? I find it helps to keep the python-numpy and cython-numpy namespaces explicitly distinct

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

if prefix == 's':
combined_prefix = 'd'
combined_cython_type = 'np.float64_t'
}}

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.

looks like a good use case for fused types!

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.

Agree. Fused types + pyx allows for coverage checks.

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 - not for initial commit, but I do like the idea of moving to fused types in the future.


cdef {{prefix}}toeplitz(int n, int o0, int o1,
{{cython_type}} [:] in_column,
{{cython_type}} [:, :] out_matrix):

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 syntax I see elsewhere usually doesn't ptu a space between the "{{cython_type}}" and the "[:"

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'd prefer to leave this as-is. I know that Pandas doesn't usually include a space, but e.g. the Cython docs do (https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html).

any output.

"""
cdef int i, j

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.

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.

Good idea

if i != j:
# Note: scipy by default does complex conjugate, but not
# necessary here since we're only dealing with covariances,
# which will be real

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.

+1 good comment

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.

Thanks!

o0 : int
The row offset for `out_matrix` at which to begin writing the Toeplitz
block.
o1 : int

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.

can you think of any more informative names than n, o0, o1?

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 think n is okay, but I'll go to offset0 and offset1

convention assumes the coefficients are part of the lag polynomial on
the left-hand-side of the ARMA definition (i.e. they have the opposite
sign from the usual econometrics convention in which the coefficients
are on the right-hand-side of the ARMA definition).

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 lack of clear naming conventions has caused trouble elsewhere. Maybe arpoly or something otherwise difficult to confuse with -ar[1:]? (ditto for ma)

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 think this is a good idea. Have we already started to do this anywhere, or do we need to establish a new convention?

@josef-pkt ? @bashtage ?

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 see that in SARIMAX I have SARIMAXResults.polynomial_reduced_ar that gives e.g. [1, -phi_1, -phi_2, ...] and SARIMAXResults.polynomial_reduced_mathat gives e.g.[1, theta_1, theta_2, ...]`.

where the model is defined as:

equation

@ChadFulton ChadFulton Dec 19, 2018 •

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.

Well I guess that model wasn't too helpful. What I mean is that the model is:

eq1

and then the lag polynomials are:

  • eq2
  • eq3

so e.g. SARIMAXReuslts.polynomial_reduced_ar gives the coefficients of \phi(L)

Edit: fixed the equation images

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.

so what about one of (listed in order of my preference):

  • ar_polynomial
  • arpoly
  • polynomial_ar

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.

Very much +1 for establishing a standard with unambiguous names and using it consistently to clear up (ar|ma)(params|coefs|poly). Slight preference for arpoly over ar_polynomial.

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.

on the other hand, we already have ar_params, so what about ar_poly?

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.

(mainly checking if my new internet connection works)

I thought we are reasonably consistent

params, ar_coeffs are econometrics estimation version
ar is lag polynomial coefficients
ar with poly in the name should be a numpy Polynomial or similar instance which can be used to directly compute with the polynomials, e.g. multiplication, inverse and so on.

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 thought we are reasonably consistent

I'd speculate that past-me would may have found ar and ma ambiguous, possibly been confused why there are both arparams and arcoeffs if they mean the same thing. I also wouldn't be surprised if there are test/example/sandbox/pseudo-sandbox files that don't follow the same conventions.

Quick look grepping for (ar|ma)_?(params|coef) suggests that code looks appreciably better than the tests consistency/clarity-wise:

ArmaProcess.__init__ takes ar and ma
ARMA.geterrors defines b, a = np.r_[1, -arparams], np.r_[1, maparams]
arma_mle does its own thing
varma_process.VarmaPoly.__init__ takes ar and ma, looks vaguely like it follows the convention.

test_arima.test_long_ar_start_params defines arparams and maparams where it should be ar and ma.
test_arima.test_arima_predict_exog has commented-out code defining arparams and maparams with leading 1s, looks inconsistent, but who knows with commented-out code.
test_arima.test_arima_1123 passes no-leading-1s arparams/maparams to arma_generate_sample, which AFAICT doesn't match the intended usage.

test_stattools.test_arma_order_select_ic starts out strong before taking its eyes off the prize:

    arparams = np.array([.75, -.25])
    maparams = np.array([.65, .35])
    arparams = np.r_[1, -arparams]
    maparam = np.r_[1, maparams]

Not going to bother looking at sandbox.

In no particular order, I'd suggest:

  • fixing (or clarifying if my reading is incorrect) the apparently-inconsistent usages in the test files (side-note: delete-or-document commented-out code)
  • adding validation in arma_generate_sample if test_arima_1123 is in fact passing invalid params (side-note: give test_arima_1123 a meaningful name)
  • using something more explicit than ar/ma, e.g. arpoly/mapoly
    • could consider going even further with this and only allow np.polynomial.Polynomial objects for these
  • settling on either (ar|ma)params or (ar|ma)coeffs, but not using both synonymously.
  • have ArmaProcess and ARMAResults share code to decrease the potential for future inconsistencies

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.

tl;dr - it sounds like a precedent already exists to use ar for the polynomial and ar_params for the econometric versions, so that's what I'll do here too.

I thought we are reasonably consistent

params, ar_coeffs are econometrics estimation version
ar is lag polynomial coefficients
ar with poly in the name should be a numpy Polynomial or similar instance which can be used to directly compute with the polynomials, e.g. multiplication, inverse and so on.

Thanks, I had forgotten about the ar vs ar_params distinction. I think you're right, that this is reasonably consistent in statsmodels as of now.

Quick look grepping for (ar|ma)_?(params|coef) suggests that code looks appreciably better than the tests consistency/clarity-wise:

Thanks for taking a look into the consistency in the existing code.

In no particular order, I'd suggest:

I support those goals, but I guess out of scope for this PR.

cdef np.npy_intp dim1[1]
cdef np.npy_intp dim2[2]
cdef {{cython_type}} [:, :] acovf
cdef {{cython_type}} [:] tmp

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.

personal preference, feel free to ignore: i like to have one cdef: and then an indented block

m2 = 2 * m
n = max(m2, nobs)

dim2[0] = n; dim2[1] = n;

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.

separate lines; no semicolons

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

@josef-pkt

Copy link
Copy Markdown
Member

needs rebase
unit test fails on some machines: test_brockwell_davis_ex534
The assert needs to specify atol, it only uses rtol when the values are zero.
e.g. atol=1e-20

there are also problems with
TypeError: can't convert complex to float
https://travis-ci.org/statsmodels/statsmodels/jobs/450045388
which might be py 3.4 or numpy 1.11 specific

@codecov

codecov Bot commented Dec 2, 2018

Copy link
Copy Markdown

Codecov Report

Merging #5360 into master will decrease coverage by 0.02%.
The diff coverage is 99.34%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5360      +/-   ##
==========================================
- Coverage   81.75%   81.72%   -0.03%     
==========================================
  Files         569      573       +4     
  Lines       89851    90068     +217     
  Branches    10022     9311     -711     
==========================================
+ Hits        73455    73611     +156     
- Misses      14126    14176      +50     
- Partials     2270     2281      +11
Impacted Files Coverage Δ
...els/tsa/innovations/tests/test_arma_innovations.py 100% <100%> (ø)
.../innovations/tests/test_cython_arma_innovations.py 100% <100%> (ø)
...vations/tests/test_cython_arma_innovations_fast.py 100% <100%> (ø)
statsmodels/tsa/arima_process.py 78.24% <92.3%> (+0.56%) ⬆️
statsmodels/tsa/innovations/arma_innovations.py 97.56% <97.56%> (ø)
statsmodels/iolib/openfile.py 66.66% <0%> (-9.1%) ⬇️
statsmodels/datasets/utils.py 78.39% <0%> (-4.94%) ⬇️
statsmodels/iolib/foreign.py 70.63% <0%> (-1.99%) ⬇️
statsmodels/base/wrapper.py 89.85% <0%> (-1.45%) ⬇️
...ar/tests/JMulTi_results/parse_jmulti_var_output.py 90.16% <0%> (-1.02%) ⬇️
... and 28 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 428b49c...d0abf26. Read the comment docs.

@codecov

codecov Bot commented Dec 2, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #5360 into master will increase coverage by 0.04%.
The diff coverage is 99.04%.

Impacted file tree graph

@@            Coverage Diff            @@
##           master   #5360      +/-   ##
=========================================
+ Coverage   81.75%   81.8%   +0.04%     
=========================================
  Files         569     574       +5     
  Lines       89824   90028     +204     
  Branches    10022   10027       +5     
=========================================
+ Hits        73440   73645     +205     
+ Misses      14117   14116       -1     
  Partials     2267    2267
Impacted Files Coverage Δ
statsmodels/tsa/api.py 100% <ø> (ø) ⬆️
statsmodels/tsa/innovations/__init__.py 100% <100%> (ø)
...els/tsa/innovations/tests/test_arma_innovations.py 100% <100%> (ø)
statsmodels/tsa/innovations/api.py 100% <100%> (ø)
...vations/tests/test_cython_arma_innovations_fast.py 100% <100%> (ø)
statsmodels/tsa/arima_process.py 78.24% <92.3%> (+0.56%) ⬆️
statsmodels/tsa/innovations/arma_innovations.py 97.56% <97.56%> (ø)
... and 4 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5b12177...b4678b8. Read the comment docs.

@ChadFulton
ChadFulton force-pushed the innov_arma branch 3 times, most recently from ea32256 to 19b7fbd Compare December 11, 2018 03:11
@ChadFulton

Copy link
Copy Markdown
Member Author

Thanks @jbrockmendel and @josef-pkt for review + comments.

unit test fails on some machines: test_brockwell_davis_ex534
The assert needs to specify atol, it only uses rtol when the values are zero.
e.g. atol=1e-20

This is now fixed,

there are also problems with
TypeError: can't convert complex to float
https://travis-ci.org/statsmodels/statsmodels/jobs/450045388
which might be py 3.4 or numpy 1.11 specific

This was a bit of a puzzle, but appears to somehow be related to the sigma2 parameter turning out to be an array rather than a scalar in number 1.11, and for some reason this gave the TypeError. This is also now fixed.

@ChadFulton

Copy link
Copy Markdown
Member Author

I think the failures are now unrelated, so we can think about what form this should take if it is to be merged into Statsmodels.

I guess my vote is to merge it basically as-is. It is not a complete model class, but it does provide: loglike, loglikeobs, score, and scoreobs for ARMA models and could even be used as-is in combination with scipy.optimize. As I mentioned above, my eventual plan is to include it as a fitting option in a model (e.g. maybe the SARIMAX model if there is no missing data, or else as a preliminary estimate on interpolated data).

One question is whether it should be exposed as part of the api somewhere (e.g. statsmodels.tsa.innovations). I don't have strong views on this,

If included as part of the API, then I need to add a documentation section for it.

Any other thoughts on what to do, or pre-merge improvements, would be welcome.

@ChadFulton

Copy link
Copy Markdown
Member Author

Okay, I have:

  1. Squashed all implementation commits that had been pushed previously:
  2. Added a new commit that removes the non-fast versions of the algorithms (so that they are in Git history, but not cluttering up the code)
  3. Added these to the API under sm.tsa.innovations, e.g. sm.tsa.innovations.arma_loglike, etc.
  4. Added their entries to the TSA documentation.

Everything was green before, and these changes shouldn't affect that, so if all is well I will plan to merge tomorrow, unless there are comments or concerns.

@ChadFulton
ChadFulton merged commit da9d7e9 into statsmodels:master Dec 27, 2018
@ChadFulton
ChadFulton deleted the innov_arma branch December 27, 2018 13:24
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