Skip to content

BUG: state space models parameters search space bands #11192

Backlog

Description

@TommasoLocatelli

Describe the bug

I have found that my implemantation of costume state space models come up with a limitation.
Whenever I perform a MLE estimation of the system parameters it seems that standard deviation counterparts of state and observation variances have a wierd behaviour.
Comparing different fir results, it seems that optimizer come up with continuous values between 0.00 and 0.01, but a strange pattern arise between 0.01 and 0.02.

statsmodels_bug

I add a photo to show what I mean.

The code is available at https://github.com/TommasoLocatelli/GRUAN_EDA

Do you have any explanation for this problem?

I will give you more details if needed.

Code Sample, a copy-pastable example

import statsmodels.api as sm
import numpy as np

"""
Univariate Local Linear Trend Model
https://www.statsmodels.org/stable/examples/notebooks/generated/statespace_local_linear_trend.html

Parameters can also be fixed 
results = model.fit_constrained({'sigma2.measurement': 0})
"""

class UnivariateLLT(sm.tsa.statespace.MLEModel):
    def __init__(self, endog, measurement_sigma2=None):
        k_states = k_posdef = 2

        # Store fixed measurement variance sequence if provided
        self.measurement_sigma2 = (
            measurement_sigma2.T if measurement_sigma2 is not None else None
        )

        super().__init__(
            endog,
            k_states=k_states,
            k_posdef=k_posdef,
            initialization="diffuse",
            loglikelihood_burn=0,
        )

        self.ssm["design"] = np.array([1, 0])
        self.ssm["transition"] = np.array([[1, 1], [0, 1]])
        self.ssm["selection"] = np.eye(k_states)

        # Univariate obs_cov
        self.ssm["obs_cov"] = np.zeros((1, 1, self.nobs))

        self._state_cov_idx = ("state_cov",) + np.diag_indices(k_posdef)

    @property
    def param_names(self):
        if self.measurement_sigma2 is None:
            return ["sigma2.measurement", "sigma2.level", "sigma2.trend"]
        else:
            return ["sigma2.level", "sigma2.trend"]

    @property
    def start_params(self):
        v = max(float(np.nanvar(self.endog)), 1e-8)

        if self.measurement_sigma2 is None:
            return [v, v, v]
        else:
            return [v, v]

    def transform_params(self, unconstrained):
        return unconstrained**2

    def untransform_params(self, constrained):
        return constrained**0.5

    def update(self, params, *args, **kwargs):
        params = super().update(params, *args, **kwargs)

        # Observation covariance
        if self.measurement_sigma2 is None:
            self.ssm["obs_cov", 0, 0] = params[0]
            state_params = params[1:]
        else:
            self.ssm["obs_cov", 0, 0] = self.measurement_sigma2[:]
            state_params = params

        # State covariance
        self.ssm[self._state_cov_idx] = state_params


"""
Univariate Local Linear Level Model (LLL)
y_t = level_t + eps_t
level_t = level_{t-1} + eta_t
"""
class UnivariateLLL(sm.tsa.statespace.MLEModel):
    def __init__(self, endog, measurement_sigma2=None):
        k_states = k_posdef = 1  # only one state: the level

        # Store fixed measurement variance sequence if provided
        self.measurement_sigma2 = (
            measurement_sigma2.T if measurement_sigma2 is not None else None
        )

        super().__init__(
            endog,
            k_states=k_states,
            k_posdef=k_posdef,
            initialization="diffuse",
            loglikelihood_burn=0,
        )

        # Observation equation: y_t = [1] * level_t
        self.ssm["design"] = np.array([1.0])

        # State transition: level_t = level_{t-1} + eta_t
        self.ssm["transition"] = np.array([[1.0]])

        # Selection matrix (noise enters the state)
        self.ssm["selection"] = np.eye(k_states)

        # Univariate obs_cov (time-varying if measurement_sigma2 is provided)
        self.ssm["obs_cov"] = np.zeros((1, 1, self.nobs))

        # Cache diagonal indices for state covariance
        self._state_cov_idx = ("state_cov",) + np.diag_indices(k_posdef)

    @property
    def param_names(self):
        if self.measurement_sigma2 is None:
            return ["sigma2.measurement", "sigma2.level"]
        else:
            return ["sigma2.level"]

    @property
    def start_params(self):
        v = max(float(np.nanvar(self.endog)), 1e-8)

        if self.measurement_sigma2 is None:
            return [v, v]
        else:
            return [v]

    def transform_params(self, unconstrained):
        # enforce positivity
        return unconstrained**2

    def untransform_params(self, constrained):
        return constrained**0.5

    def update(self, params, *args, **kwargs):
        params = super().update(params, *args, **kwargs)

        # Measurement noise variance
        if self.measurement_sigma2 is None:
            # scalar parameter
            self.ssm["obs_cov", 0, 0] = params[0]
            state_params = params[1:]
        else:
            # fixed time-varying measurement variance
            self.ssm["obs_cov", 0, 0] = self.measurement_sigma2[:]
            state_params = params

        # State noise variance (level innovation)
        self.ssm[self._state_cov_idx] = state_params

class DeterministicLevelLLT(sm.tsa.statespace.MLEModel):
    """
    Local Linear Trend model with deterministic level:
        level_t = level_{t-1} + trend_{t-1}
        trend_t = trend_{t-1} + η_t,   η_t ~ N(0, σ²_trend)
        y_t = level_t + ε_t,          ε_t ~ N(0, σ²_measurement)
    """

    def __init__(self, endog, measurement_sigma2=None):
        k_states = 2
        k_posdef = 2  # Q is 2x2 but level variance will be fixed at zero

        self.measurement_sigma2 = (
            measurement_sigma2.T if measurement_sigma2 is not None else None
        )

        super().__init__(
            endog,
            k_states=k_states,
            k_posdef=k_posdef,
            initialization="diffuse",
            loglikelihood_burn=0,
        )

        # State-space matrices
        self.ssm["design"] = np.array([1, 0])
        self.ssm["transition"] = np.array([[1, 1],
                                           [0, 1]])
        self.ssm["selection"] = np.eye(k_states)

        # Time-varying obs_cov
        self.ssm["obs_cov"] = np.zeros((1, 1, self.nobs))

        # Index for diagonal of state covariance
        self._state_cov_idx = ("state_cov",) + np.diag_indices(k_posdef)

    # Only trend variance is estimated
    @property
    def param_names(self):
        if self.measurement_sigma2 is None:
            return ["sigma2.measurement", "sigma2.trend"]
        else:
            return ["sigma2.trend"]

    @property
    def start_params(self):
        if self.measurement_sigma2 is None:
            return [np.var(self.endog), np.var(self.endog)]
        else:
            return [np.var(self.endog)]

    def transform_params(self, unconstrained):
        return unconstrained**2

    def untransform_params(self, constrained):
        return constrained**0.5

    def update(self, params, *args, **kwargs):
        params = super().update(params, *args, **kwargs)

        # Observation variance
        if self.measurement_sigma2 is None:
            meas_var = params[0]
            trend_var = params[1]
        else:
            meas_var = self.measurement_sigma2[:]
            trend_var = params[0]

        self.ssm["obs_cov", 0, 0] = meas_var

        # State covariance Q:
        # level variance = 0 (deterministic)
        # trend variance = trend_var
        self.ssm["state_cov", 0, 0] = 0.0
        self.ssm["state_cov", 1, 1] = trend_var

        return params

Expected Output

with respect to the added photo, I would expect contiuous values candidates

Actual Output

# optimizer seems to be stick to a grid

Versions

INSTALLED VERSIONS
------------------
Python: 3.11.9.final.0

statsmodels
===========

Installed: 0.14.6 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\statsmodels)

Required Dependencies
=====================

cython: Not installed
numpy: 1.26.4 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\numpy)
scipy: 1.11.4 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\scipy)
pandas: 2.2.3 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\pandas)
    dateutil: 2.9.0.post0 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\dateutil)
patsy: 1.0.2 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\patsy)

Optional Dependencies
=====================

matplotlib: 3.10.1 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\matplotlib)
    backend: tkagg 
cvxopt: Not installed
joblib: 1.5.3 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\joblib)

Developer Tools
================

IPython: 9.15.0 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\IPython)
    jinja2: Not installed
sphinx: Not installed
    pygments: 2.20.0 (C:\Users\tomma\Documents\SDC\Repos\GRUAN_EDA\.venv\Lib\site-packages\pygments)
pytest: Not installed
virtualenv: Not installed

Checklist

  • I have searched the issue tracker for a similar issue and did not find one.

  • I have confirmed this bug exists on the latest released version of statsmodels, or on the main branch.

Activity

  1. ChenyangLi4288 commented on Nov 24, 2026

    @ChenyangLi4288
    Contributor

    Thanks for the detailed report. I believe this comes from how the estimates are being read rather than from the optimizer. The bands sit at
    $σ = 0.01·\sqrt{k}$, so $σ²$ is landing exactly on multiples of 1e-4. That's the formatting used in results.summary(): values below 1e-4 are printed to 4 significant figures and larger ones to 4 decimal places. That gives a continuous region below σ = 0.01 and a grid above it.

    I reproduced this with your UnivariateLLT: results.params is continuous, and the same fits read back from results.summary().tables[1] fall exactly on the grid. Could you check whether your plotting script takes the values from the summary table, printed output, or a file saved with 4 decimals?

    Using results.params directly should solve.

  2. TommasoLocatelli commented on Nov 25, 2026

    @TommasoLocatelli
    Author

    It seems you are right! The preliminary tests using results.params instead of results.summary() seems to fix the behaviour.
    Thank you 🙏

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions