Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of vectorizing ruptures with xarray.apply_ufunc #136

Closed
spencerahill opened this issue Mar 9, 2021 · 2 comments
Closed

Example of vectorizing ruptures with xarray.apply_ufunc #136

spencerahill opened this issue Mar 9, 2021 · 2 comments

Comments

@spencerahill
Copy link

spencerahill commented Mar 9, 2021

In case others come across a similar need (whether or not it makes sense to implement this into ruptures proper), here's a way of using xarray.apply_ufunc to perform calculations on rupture on xarray.DataArrays.

This particular example is for detecting a single breakpoint; note that if you want to return multiple, the apply_ufunc call signature will have to be modified, because then each call is returning an array rather than a scalar.

import ruptures as rpt
import xarray as xr

def detect_breakpoint(arr, dim, rpt_class=rpt.Binseg, model="l2", n_bkps=1):
    """Use xr.apply_ufunc to broadcast breakpoint detections from ruptures"""

    def _detect_bp(arr):
        """Wrapper to use in apply_ufunc."""
        return rpt_class(model=model).fit(arr).predict(n_bkps=n_bkps)[0]

    inds_bp = xr.apply_ufunc(
        _detect_bp,
        arr,
        input_core_dims=[[dim]],
        vectorize=True,
        dask="parallelized",
    )
    return arr[dim][inds_bp]

(FYI This came up when attempting to detect changepoints at each point of a lat-lon gridded rainfall dataset.)

@oboulant
Copy link
Collaborator

Hi @spencerahill ,

Thanks for your interest in ruptures !

Since this is more of a discussion/hint than an issue, could you please move this to the discussion section ?

Best,

Olivier

@spencerahill
Copy link
Author

Done! #139

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants