Skip to content

Unable to avoid copy while creating an array as requested #326

Open

Description

@jclsn

Hi, I am currently trying to execute the code in your Notebook on Kalman filters. In the Multivariate Gaussians section this error is thrown, which seems to be an allocation problem in filterpy

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[19], line 7
      3 mean = [2., 17.]
      4 cov = [[10., 0.], 
      5        [0., 4.]]
----> 7 mkf_internal.plot_3d_covariance(mean, cov)

File [~/work/Kalman-and-Bayesian-Filters-in-Python/kf_book/mkf_internal.py:283](/user/jan/lab/tree/Kalman-and-Bayesian-Filters-in-Python/Kalman-and-Bayesian-Filters-in-Python/kf_book/mkf_internal.py#line=282), in plot_3d_covariance(mean, cov)
    280 ys = np.arange(miny, maxy, (maxy-miny)[/40.](/40.))
    281 xv, yv = np.meshgrid(xs, ys)
--> 283 zs = np.array([100.* stats.multivariate_gaussian(np.array([x, y]), mean, cov) \
    284                for x, y in zip(np.ravel(xv), np.ravel(yv))])
    285 zv = zs.reshape(xv.shape)
    287 fig = plt.figure()

File [/opt/conda/lib/python3.12/site-packages/filterpy/stats/stats.py:382](/opt/conda/lib/python3.12/site-packages/filterpy/stats/stats.py#line=381), in multivariate_gaussian(x, mu, cov)
    380 # force all to numpy.array type, and flatten in case they are vectors
    381 x = np.array(x, copy=False, ndmin=1).flatten()
--> 382 mu = np.array(mu, copy=False, ndmin=1).flatten()
    384 nx = len(mu)
    385 cov = _to_cov(cov, nx)

ValueError: Unable to avoid copy while creating an array as requested.
If using `np.array(obj, copy=False)` replace it with `np.asarray(obj)` to allow a copy when needed (no behavior change in NumPy 1.x).
For more details, see https://numpy.org/devdocs/numpy_2_0_migration_guide.html#adapting-to-changes-in-the-copy-keyword.
``

Activity

  1. Meikul commented on Jun 28, 2026

    @Meikul

    I'm also running into this issue in chapter 5 unfortunately. I installed the project dependencies via the conda environment.yml file. and I've tried changing the versions of some packages, but I've had no luck.

  2. jclsn commented on Jun 29, 2026

    @jclsn
    Author

    @Meikul: I patched the mahalanobis and likelihood functions by replacing them with this

     def _safe_mahalanobis(self):
         if self._mahalanobis is None:
             y = np.atleast_2d(self.y)
             if y.shape[0] == 1:
                 y = y.T
             SI = np.atleast_2d(self.SI)
             self._mahalanobis = np.sqrt((y.T @ SI @ y).item())
         return self._mahalanobis
     
     def _safe_likelihood(self):
         if self._likelihood is None:
             self._likelihood = exp(self.log_likelihood)
             if self._likelihood == 0:
                 self._likelihood = sys.float_info.min
         return self._likelihood

    Haven't had any issues since. Since I built myself a JupyterLab Docker container with the book baked in, I used a sitecustomize.py

    # sitecustomize.py
    import numpy as np
    import sys
    import warnings
    
    from math import exp
    from filterpy.kalman import KalmanFilter
    
    warnings.filterwarnings(
        "ignore",
        category=SyntaxWarning,
        message=r".*invalid escape sequence.*"
    )
    
    def _safe_mahalanobis(self):
        if self._mahalanobis is None:
            y = np.atleast_2d(self.y)
            if y.shape[0] == 1:
                y = y.T
            SI = np.atleast_2d(self.SI)
            self._mahalanobis = np.sqrt((y.T @ SI @ y).it
        return self._mahalanobis
    
    def _safe_likelihood(self):
        if self._likelihood is None:
            self._likelihood = exp(self.log_likelihood)
            if self._likelihood == 0:
                self._likelihood = sys.float_info.min
        return self._likelihood
    
    KalmanFilter.mahalanobis = property(_safe_mahalanobis
    KalmanFilter.likelihood = property(_safe_likelihood) 

    Which I put into /opt/conda/lib/python3.1/site-packages/. This is probably the easiest approach for you as well. You should probably put it into ~/.local/lib/python3.x depending on your setup though.

    Unfortunately @rlabbe is not really responding anymore, so I didn't bother to send a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions