Skip to content

ENH: Control Charts #4191

Open
Open

Description

@josef-pkt

Getting started with Control Charts, mainly multivariate where statistics is similar to several other issues.
I put a script in the next comment with some experiments done in a few hours.
(Issue so I find this again, I will come back to it another time.)

current reference:
Bersimis, Psarakis, Panaretos (2007): Multivariate Statistical Process Control Charts: An Overview

many open design issues

example Hotelling T2 shewart chart (one observation)

3 distributions for mahalanobis distance (details somewhere in a robust issue or PR)

  • chisquare: in large samples or known covariance
  • beta: insample estimate of covariance, evaluation of in-sample observation
  • F: covariance estimated in a different sample, evaluation of out-of-sample observation

in control charts: beta is used in phase one, F is used in phase two
that is we need to distinguish of an observation is in-sample or out-of-sample

what information do we need and keep track of:

  • "static" charts like shewart chart
    • need only mean and standard deviation or control limits
    • we need estimation sample for updating the estimates
    • we need some history, recent observations if we want to plot
  • "dynamic" charts like EWMA or CUSUM
    • need also last "state" to evaluate next observation, others are the same

Note: sample for updating estimation and sample for plotting with recent history do not use the same observations if the history includes out-of-control/outlier observations. Those are plotted but not included in the estimation.

Sheward, EWMA or CUSUM are the basic charts, but then we also have model based charts, e.g. using regression or time series models with charting of residuals or forecast error, and decomposition, PCA, PLS, based charts.

a different pattern are self-starting and automatic updating charts: those don't distinguish between phase 1 estimation and phase 2 charting.

current version 3 classes with largely copy-paste because I don't know what the common attributes will be.

MEWMA doesn't have explicit distribution for control limits. The usual method seems to be simulation, but bootstrap is also possible.

Activity

  1. josef-pkt commented on Jan 6, 2018

    @josef-pkt
    MemberAuthor
    # -*- coding: utf-8 -*-
    """Control Charts and Statistical Process Control
    
    Created on Sun Dec 31 23:47:52 2017
    
    Author: Josef Perktold
    
    
    Some tools for building control charts and process monitoring.
    The core should be tools for the statistics, estimation and control limits.
    Control charts and monitoring interface are just for a basic example use case.
    
    """
    
    from __future__ import division
    import numpy as np
    from scipy import stats
    import matplotlib.pyplot as plt
    
    def update_std(std, nobs, y_new):
        raise NotImplementedError
        
    class Holder(object):
        def __init__(self, **kwds):
            self.__dict__.update(kwds)
        
    def control_limits_mean(y0, alpha=0.05, crit=None, distr='t'):
            
            endog = y0
            nobs = endog.shape[0]
            #index = np.arange(nobs)  # not used nor returned
            
            if crit is not None:
                crit = crit
            else:
                if distr == 't':
                    crit = stats.t.isf(alpha/2, nobs-1)
                elif distr == 'n':
                    crit = stats.norm.isf(alpha/2)
                else:
                    raise ValueError('only t and normal for now' )
    
            center = endog.mean(0)
            std = endog.std(0, ddof=1)
            diff = crit * std
            upp = center + diff
            low = center - diff
            res = Holder(center=center,
                         std=std,
                         low=low,
                         upp=upp,
                         diff=diff)
            return res
            
    
    class ControlChartMean(object):
        
        def __init__(self, y0, alpha=0.05, crit=None, distr='t'):
            
            self.endog = y0
            self.nobs = self.endog.shape[0]
            self.index = np.arange(self.nobs)
            
            if crit is not None:
                self.crit = crit
            else:
                if distr == 't':
                    self.crit = stats.t.isf(alpha/2, self.nobs-1)
                elif distr == 'n':
                    self.crit = stats.norm.isf(alpha/2)
                else:
                    raise ValueError('only t and normal for now' )
    
            self.center = self.endog.mean(0)
            self.std = self.endog.std(0, ddof=1)
            self.diff = self.crit * self.std
            self.upp = self.center + self.diff
            self.low = self.center - self.diff
    
        def plot_chart(self, y_new, include_y0=True, ax=None):
            if include_y0 is True:
                y = np.concatenate((self.endog, y_new), axis=0)
            n1 = y_new.shape[0]
            idx_new = np.arange(self.index[-1] + 1, self.index[-1] + 1 + n1)
            idx = np.concatenate((self.index, idx_new))
            self.idx = idx
            
            if ax is None:
                fig = plt.figure()
                ax = fig.add_subplot(111)
            if np.isscalar(self.upp) or True:
                ax.hlines(self.upp, idx[0], idx[-1], colors='k')
                ax.hlines(self.low, idx[0], idx[-1], colors='k')
                ax.hlines(self.center, idx[0], idx[-1], lw=2, colors='k')
            else:
                ax.plot(idx, self.upp, color='k')
                ax.plot(idx, self.low, color='k')
                ax.plot(idx, self.center, lw=2, color='k')
            
            out = (y > self.upp) | (y < self.low)
            ax.plot(idx, y, 'o-') #, color='b')
            if y.ndim > 1:
                idx_out = np.repeat(np.arange(y.shape[0])[:,None], y.shape[1], axis=1)[out]
            else:
                idx_out = idx[out]
            ax.plot(idx_out, y[out], 'o', color='red')
            ax.set_xlim(idx[0], idx[-1])
            ax.vlines(idx[self.nobs], *ax.get_ylim())
            ax.set_title('Mean Chart vectorized')
            return fig
            
        def update(self, y_new):
            n1 = y_new.shape[0]
            n0 = self.nobs
            self.center = (n0 * self.center + y_new.sum(0)) / (n0+n1)
            self.endog = np.concatenate((self.endog, y_new), axis=0)
            idx_new = np.arange(self.index[-1] + 1, self.index[-1] + 1 + n1)
            self.index = np.concatenate((self.index, idx_new))
            # no updating formula yet
            self.std = self.endog.std(0)
            self.nobs += n1
            self.diff = self.crit * self.std
            self.upp = self.center + self.diff
            self.low = self.center - self.diff
            
            
    class ControlChartMvMean(ControlChartMean):
        """T2 control chart for multivariate mean
        """
        
        def __init__(self, y0, alpha=0.05, crit=None, distr='F'):
            
            self.endog = y0
            self.nobs, self.k_endog = self.endog.shape
            self.index = np.arange(self.nobs)
            
            if crit is not None:
                self.crit = crit
            else:
                if distr == 'F':
                    self.crit = stats.f.isf(alpha/2, 1, self.nobs-1)
                elif distr == 'chi2':
                    self.crit = stats.chi2.isf(alpha/2, 1)
                else:
                    raise ValueError('only t and normal for now' )
    
            
            self.center = self.endog.mean(0)
            
            self.cov = np.cov(self.endog, rowvar=0, ddof=1)
            self.cov_inv = np.linalg.inv(self.cov)
            diff = self.endog - self.center
            distance = (diff.dot(self.cov_inv) * diff).sum(1)
            self.c = (self.nobs - 1)**2 / self.nobs
            self.statistic = distance / self.c
            df1 = self.k_endog / 2
            df2 = (self.nobs - self.k_endog - 1) / 2
            #self.upp = self.c * stats.beta.isf(alpha, df1, df2)
            self.upp = stats.beta.isf(alpha, df1, df2)
            self.low = 0
            
        def plot_chart(self, y_new, include_y0=True, ax=None):
            diff_new = y_new - self.center
            stat_new = (diff_new.dot(self.cov_inv) * diff_new).sum(1) / self.c
            df1 = self.k_endog / 2
            if include_y0 is True:
                y = np.concatenate((self.statistic, stat_new), axis=0)
            n1 = y_new.shape[0]
            idx_new = np.arange(self.index[-1] + 1, self.index[-1] + 1 + n1)
            idx = np.concatenate((self.index, idx_new))
            self.idx = idx
            
            if ax is None:
                fig = plt.figure()
                ax = fig.add_subplot(111)
            if np.isscalar(self.upp) or True:
                ax.hlines(self.upp, idx[0], idx[-1], colors='k')
                ax.hlines(self.low, idx[0], idx[-1], colors='k')
                #ax.hlines(y, idx[0], idx[-1], lw=2, colors='k')
            else:
                ax.plot(idx, self.upp, color='k')
                ax.plot(idx, self.low, color='k')
                ax.plot(idx, self.statistic, lw=2, color='k')
            
            out = (y > self.upp) | (y < self.low)
            ax.plot(idx, y, 'o-') #, color='b')
            if y.ndim > 1:
                idx_out = np.repeat(np.arange(y.shape[0])[:,None], y.shape[1], axis=1)[out]
            else:
                idx_out = idx[out]
            ax.plot(idx_out, y[out], 'o', color='red')
            ax.set_xlim(idx[0], idx[-1])
            ax.vlines(idx[self.nobs], *ax.get_ylim())
            ax.set_title('Multivariate Mean Chart T2')
            return fig
    
    class ControlChartEWMAMvMean(ControlChartMean):
        """T2 control chart for multivariate mean
        """
        
        def __init__(self, y0, weights, alpha=0.05, crit=None, distr='F'):
            
            self.endog = y0
            self.nobs, self.k_endog = self.endog.shape
            self.index = np.arange(self.nobs)
            self.w = w = weights
            
            if crit is not None:
                self.crit = crit
            else:
                if distr == 'F':
                    self.crit = stats.f.isf(alpha/2, 1, self.nobs-1)
                elif distr == 'chi2':
                    self.crit = stats.chi2.isf(alpha/2, 1)
                else:
                    raise ValueError('only t and normal for now' )
    
            
            self.center = self.endog.mean(0)
            
            self.cov = np.cov(self.endog, rowvar=0, ddof=1)
            
            self.cov = np.cov(self.endog, rowvar=0, ddof=1)
            wt = w / (2. - w)
            self.cov_z = wt * self.cov * wt[:, None]
            self.cov_z_inv = np.linalg.inv(self.cov_z)
            z0 = self.endog.mean(0)
            self.z = z = self._generate_mewma(self.endog, z0, w)
            diff = np.asarray(z)
            distance = (diff.dot(self.cov_z_inv) * diff).sum(1)
            self.c = (self.nobs - 1)**2 / self.nobs
            self.statistic = distance / self.c
            df1 = self.k_endog / 2
            df2 = (self.nobs - self.k_endog - 1) / 2
            #self.upp = self.c * stats.beta.isf(alpha, df1, df2)
            self.upp = 0.5 #stats.beta.isf(alpha, df1, df2)
            self.low = 0
            
        def _generate_mewma(self, endog, z0, w):
            """using explicit loop for now
            """
            if endog.ndim == 2:
                n, k_endog = endog.shape
            elif endog.ndim == 0:
                n = 1
            z = [z0]
            for t in range(n):
                z.append(z[-1] + w * (endog[t] - z[-1]))
            return z[1:]
                
            
        def plot_chart(self, y_new, include_y0=True, ax=None):
            z = self._generate_mewma(y_new, self.z[-1], self.w)
            diff_new = np.asarray(z)
            stat_new = (diff_new.dot(self.cov_z_inv) * diff_new).sum(1) / self.c
            df1 = self.k_endog / 2
            if include_y0 is True:
                y = np.concatenate((self.statistic, stat_new), axis=0)
            n1 = y_new.shape[0]
            idx_new = np.arange(self.index[-1] + 1, self.index[-1] + 1 + n1)
            idx = np.concatenate((self.index, idx_new))
            self.idx = idx
            
            if ax is None:
                fig = plt.figure()
                ax = fig.add_subplot(111)
            if np.isscalar(self.upp) or True:
                ax.hlines(self.upp, idx[0], idx[-1], colors='k')
                ax.hlines(self.low, idx[0], idx[-1], colors='k')
                #ax.hlines(y, idx[0], idx[-1], lw=2, colors='k')
            else:
                ax.plot(idx, self.upp, color='k')
                ax.plot(idx, self.low, color='k')
                ax.plot(idx, self.statistic, lw=2, color='k')
            
            out = (y > self.upp) | (y < self.low)
            ax.plot(idx, y, 'o-') #, color='b')
            if y.ndim > 1:
                idx_out = np.repeat(np.arange(y.shape[0])[:,None], y.shape[1], axis=1)[out]
            else:
                idx_out = idx[out]
            ax.plot(idx_out, y[out], 'o', color='red')
            ax.set_xlim(idx[0], idx[-1])
            ax.vlines(idx[self.nobs], *ax.get_ylim())
            ax.set_title('MEMWA Chart')
            return fig
            
    
    nobs = 100
    y = np.random.randn(nobs,2)
    idx = np.arange(nobs)
    y[50:60] += 1
    y[80:90] += 2
    
    alpha = 0.05
    
    n0 = nobs//2
    y0 = y[:n0]
    m = y0.mean(0)
    std = y0.std(0, ddof=1)
    c4 = 1 #np.nan not yet
    
    
    if 0:
        # initial plot, univariate only
        z = (y - m) / std
        diff = stats.t.isf(alpha/2, n0-1) * std
        upp = m + diff
        low = m - diff
    
    
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.hlines(upp, idx[0], idx[-1], colors='k')
        ax.hlines(low, idx[0], idx[-1], colors='k')
        ax.hlines(m, idx[0], idx[-1], colors='k')
        
        out = (y > upp) | (y < low)
        ax.plot(idx, y, 'o-', color='b')
        ax.plot(idx[out], y[out], 'o', color='red')
        ax.set_xlim(idx[0], idx[-1])
        ax.vlines(idx[n0], *ax.get_ylim())
    
    
    runall = True
    if runall:
        qc = ControlChartMean(y0)
        qc.plot_chart(y[n0:])
        print(qc.center, qc.std)
        qc.update(y[n0:n0+10])
        qc.plot_chart(y[n0+10:])
        print(qc.center, qc.std)
        
        qc_mv = ControlChartMvMean(y0[:n0])
        qc_mv.plot_chart(y[n0:])
    
    qc_memwa = ControlChartEWMAMvMean(y0[:n0], np.array([0.5, 0.5]))
    qc_memwa.plot_chart(y[n0:])
    
    plt.show()
    
    
  2. shangyian commented on Feb 15, 2019

    @shangyian

    Out of curiosity, is this still being worked on? I'm interested in working on something similar that might fit this usecase.

  3. josef-pkt commented on Feb 15, 2019

    @josef-pkt
    MemberAuthor

    It's one of my long term side projects.
    My main problem is that I don't know what would make a good API and what would be useful user facing functions or methods for this. That's the main reason the above is in a script and not a PR.

    I was also working on related hypothesis test as background for control charts but with more general applicability, like #4107 for multivariate hypothesis test which we don't have yet.

    If you can provide ideas and feedback for the API design and possibly work on it, then we could get started with adding this to statsmodels.

    @shangyian What's your usecase, datasize, type of data, ...?

  4. shangyian commented on Feb 16, 2019

    @shangyian

    Yeah, I think the API design part is complicated since it depends on exactly what people want to use it for.

    In my case, I was building a control chart for CUSUM and EWMA (specifically for event count timeseries data), but I was only planning on using the control chart to replay over (and visualize) historical data as a way of validating the control chart's performance. I can also see it being useful to extend control charts to time series modelling (i.e., seasonal decomposition and charting control limits over the residuals).

    I think for the purposes of generalization, the control chart should be able to handle arbitrary functions for the upper/lower control limits, along with some default, commonly used ones.

    The other thing is that something like CUSUM itself can be broadly generalized, since the decision weights can be an arbitrary function, even though in practice the likelihood ratio is often used.
    I.e., in $$S_i = max(0, S_{i−1} + D_i)$$ we can assign whatever we want to $D_i$ and it would just be a framework for collecting the statistic.

    In any case, these are all use cases that don't involve streaming updates, but I'm assuming something like that would be out of scope for statsmodels.

  5. josef-pkt commented on Feb 16, 2019

    @josef-pkt
    MemberAuthor

    I was only planning on using the control chart to replay over (and visualize) historical data as a way of validating the control chart's performance.

    That sounds like a good usecase that we can target with the implementation. There are several python packages for monitoring and charting that do all the data handling.
    If we target prototyping and evaluation of control chart performance, then we don't have to worry directly about how the control charts are tied into the larger system and e.g. about how the real-time monitoring works.
    We still need updating of control charts but only to simulate the process and charts for historical or artificial data.

    We do get questions about pickling and updating in time series models, so there are use cases where models, prediction and forecasting are directly used "in production". But we can look at that when it shows up, if it ever does.

  6. josef-pkt commented on Feb 16, 2019

    @josef-pkt
    MemberAuthor

    I converted my script to a notebook so it's easier to see the plots
    https://gist.github.com/josef-pkt/8a2893dd2a22e9724eb6417d493955b2

    I think we can put control_charts as module in statsmodels.stats. I guess it will not get large enough in the near future to use a separate directory for it. It can always be moved later if needed.

  7. shangyian commented on Feb 16, 2019

    @shangyian

    I agree that it's better to stick to prototyping/evaluation of control charts rather than an actual production system. It's also much harder to design for the latter without knowledge of the size and source of the data streams. For my work, I will eventually be building real-time monitoring control charts, but that's for later..

    Nice! Do you have a branch you're working off somewhere? Maybe I can try to add a CUSUM component that builds off of what you have so far.

  8. shangyian commented on Feb 16, 2019

    @shangyian

    Scratch that, I see the PR! 👍

  9. josef-pkt commented on Feb 17, 2019

    @josef-pkt
    MemberAuthor

    @shangyian Are you able to work off my PR branch?
    Do you know R to write some unit tests?

    I think we could merge some initial, experimental version pretty soon, and then enhance and refactor directly for master.
    My guess is that the base functionality and API should be pretty stable, but that we will need some time to get the code structure in an appropriate form. There are a large number of options and cases of control charts, so we will need a structure that makes it easy to add new options and methods reusing a general modular structure of classes and helper functions.

    e.g. I think

    • we need 3 types of chart methods, Xbar style, CUSUM and EMWA.
    • plotting should be generic and use common consistent names, e.g. statistic, center, upp and low, partially independent of the internal computation, e.g. plotting x(bar)-charts and t-charts in the same class, or plotting transformed variables in Poisson or proportion charts

    I think we can stick at the beginning with requiring "clean" samples for the estimation and update, i.e. outlier removal has to be done by the user or caller.

    I'm not sure how to best include subgroup charts, i.e. whether an observation is a single item or an average of several items. If the group or batch size is constant, then it will not matter much, but if batch size varies, then we need std to depend on the batch size. (Related if we have systematic variation in variance/std.)

    excess dispersion in count variables, proportion (Binomial p-chart) and rates (Poisson c-chart or u-chart)
    minitab documentation uses "Laney P' and U'" charts to estimate and account for excess dispersion https://support.minitab.com/en-us/minitab/18/Assistant_Attribute_Control_Charts.pdf

    another article uses Agresti Coull interval for proportions (which we have in stats.proportions)
    Wang, Hsiuying. "Comparison of p control charts for low defective rate." Computational Statistics & Data Analysis 53, no. 12 (2009): 4210-4220.
    It looks like for Binomial and Poisson counts the situation with small sample approximation is similar to what we have in hypothesis tests and confidence intervals for rates and proportions.

    (Aside: It's easy to get lost in this literature. There are a large number of variations for each type of chart, and the number of citations for articles are pretty low in most cases.)

  10. josef-pkt commented on Feb 17, 2019

    @josef-pkt
    MemberAuthor

    recent developments in 2014
    William H. Woodall & Douglas C. Montgomery (2014) Some Current Directions in the Theory and Application of Statistical Process Monitoring, Journal of Quality Technology, 46:1, 78-94, DOI: 10.1080/00224065.2014.11917955
    looks useful to provide some extension ideas, variable selection, large data, parameter uncertainty, nonparametric, and to show what the researchers in the field consider important.

  11. shangyian commented on Feb 18, 2019

    @shangyian

    Yup I can work off your PR branch!

    It's been a while since I've worked with R, but I will try. It looks like the most up-to-date R package for control charts is this one: https://anhoej.github.io/qicharts2/

    I have indeed been getting lost in the literature... It seems like there are many aspects that can be customized for all the different charts, but most of that can be left for later customization. I'm going to try to do some light refactoring so that some of the distribution computations can be reused across control charts.

  12. josef-pkt commented on Feb 18, 2019

    @josef-pkt
    MemberAuthor

    @shangyian As a reminder: Most R packages are GPL licensed which is not compatible with our BSD-3 license. So we can use them for unit tests and the documentation, but we are not allowed to copy/translate the code.

    Do you also want to create a base class and refactor the plot method, or should I do this before going back to other issues and PRs?

    for unit tests: I have Stata which I most often use for unit tests, but they have only the very basic charts with just 3 sigma limits. And they use the range statistic for std, which from what I remember reading is not very efficient.

  13. shangyian commented on Feb 18, 2019

    @shangyian

    I can work on creating a base class and refactoring plot.

    I'll make sure to reference papers for the control chart implementations. And just use R packages for verification in the unit tests.

  14. josef-pkt commented on Feb 19, 2019

    @josef-pkt
    MemberAuthor

    Good, if you want to take over this part, then you could push a checkout of my branch to your github repo and open a new PR against statsmodels master.
    In that case, you would get the CI test runs immediately after you push changes to your branch. I will then be reviewing the code, and eventually merge it without being involved in all changes.

  15. shangyian commented on Feb 19, 2019

    @shangyian

    Sounds good, just did that here: #5506

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions