{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Weighted Generalized Linear Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import statsmodels.formula.api as smf\n",
    "import statsmodels.api as sm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Weighted GLM: Poisson response data\n",
    "\n",
    "### Load data\n",
    "\n",
    "In this example, we'll use the affair dataset using a handful of exogenous variables to predict the extra-marital affair rate. \n",
    "\n",
    "Weights will be generated to show that `freq_weights` are equivalent to repeating records of data. On the other hand, `var_weights` is equivalent to aggregating data.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "print(sm.datasets.fair.NOTE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load the data into a pandas dataframe."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = sm.datasets.fair.load_pandas().data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " The dependent (endogenous) variable is ``affairs``"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "data.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "data[:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following we will work mostly with Poisson. While using decimal affairs works, we convert them to integers to have a count distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "data[\"affairs\"] = np.ceil(data[\"affairs\"])\n",
    "data[:3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(data[\"affairs\"] == 0).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "np.bincount(data[\"affairs\"].astype(int))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Condensing and Aggregating observations\n",
    "\n",
    "We have 6366 observations in our original dataset. When we consider only some selected variables, then we have fewer unique observations. In the following we combine observations in two ways, first we combine observations that have values for all variables identical, and secondly we combine observations that have the same explanatory variables."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset with unique observations\n",
    "\n",
    "We use pandas's groupby to combine identical observations and create a new variable `freq` that count how many observation have the values in the corresponding row."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "data2 = data.copy()\n",
    "data2[\"const\"] = 1\n",
    "dc = (\n",
    "    data2[\"affairs rate_marriage age yrs_married const\".split()]\n",
    "    .groupby(\"affairs rate_marriage age yrs_married\".split())\n",
    "    .count()\n",
    ")\n",
    "dc.reset_index(inplace=True)\n",
    "dc.rename(columns={\"const\": \"freq\"}, inplace=True)\n",
    "print(dc.shape)\n",
    "dc.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset with unique explanatory variables (exog)\n",
    "\n",
    "For the next dataset we combine observations that have the same values of the explanatory variables. However, because the response variable can differ among combined observations, we compute the mean and the sum of the response variable for all combined observations.\n",
    "\n",
    "We use again pandas ``groupby`` to combine observations and to create the new variables. We also flatten the ``MultiIndex`` into a simple index."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gr = data[\"affairs rate_marriage age yrs_married\".split()].groupby(\n",
    "    \"rate_marriage age yrs_married\".split()\n",
    ")\n",
    "df_a = gr.agg([\"mean\", \"sum\", \"count\"])\n",
    "\n",
    "\n",
    "def merge_tuple(tpl):\n",
    "    if isinstance(tpl, tuple) and len(tpl) > 1:\n",
    "        return \"_\".join(map(str, tpl))\n",
    "    else:\n",
    "        return tpl\n",
    "\n",
    "\n",
    "df_a.columns = df_a.columns.map(merge_tuple)\n",
    "df_a.reset_index(inplace=True)\n",
    "print(df_a.shape)\n",
    "df_a.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After combining observations with have a dataframe `dc` with 467 unique observations, and a dataframe `df_a` with 130 observations with unique values of the explanatory variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "print(\"number of rows: \\noriginal, with unique observations, with unique exog\")\n",
    "data.shape[0], dc.shape[0], df_a.shape[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Analysis\n",
    "\n",
    "In the following, we compare the GLM-Poisson results of the original data with models of the combined observations where the multiplicity or aggregation is given by weights or exposure.\n",
    "\n",
    "\n",
    "### original data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs ~ rate_marriage + age + yrs_married\",\n",
    "    data=data,\n",
    "    family=sm.families.Poisson(),\n",
    ")\n",
    "res_o = glm.fit()\n",
    "print(res_o.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_o.pearson_chi2 / res_o.df_resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### condensed data (unique observations with frequencies)\n",
    "\n",
    "Combining identical observations and using frequency weights to take into account the multiplicity of observations produces exactly the same results. Some results attribute will differ when we want to have information about the observation and not about the aggregate of all identical observations. For example, residuals do not take ``freq_weights`` into account."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs ~ rate_marriage + age + yrs_married\",\n",
    "    data=dc,\n",
    "    family=sm.families.Poisson(),\n",
    "    freq_weights=np.asarray(dc[\"freq\"]),\n",
    ")\n",
    "res_f = glm.fit()\n",
    "print(res_f.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_f.pearson_chi2 / res_f.df_resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### condensed using ``var_weights`` instead of ``freq_weights``\n",
    "\n",
    "Next, we compare ``var_weights`` to ``freq_weights``. It is a common practice to incorporate ``var_weights`` when the endogenous variable reflects averages and not identical observations.\n",
    "I do not see a theoretical reason why it produces the same results (in general).\n",
    "\n",
    "This produces the same results but ``df_resid``  differs the ``freq_weights`` example because ``var_weights`` do not change the number of effective observations.  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs ~ rate_marriage + age + yrs_married\",\n",
    "    data=dc,\n",
    "    family=sm.families.Poisson(),\n",
    "    var_weights=np.asarray(dc[\"freq\"]),\n",
    ")\n",
    "res_fv = glm.fit()\n",
    "print(res_fv.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dispersion computed from the results is incorrect because of wrong ``df_resid``. \n",
    "It is correct if we use the original ``df_resid``."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_fv.pearson_chi2 / res_fv.df_resid, res_f.pearson_chi2 / res_f.df_resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### aggregated or averaged data (unique values of explanatory variables)\n",
    "\n",
    "For these cases we combine observations that have the same values of the explanatory variables. The corresponding response variable is either a sum or an average.\n",
    "\n",
    "#### using ``exposure``\n",
    "\n",
    "If our dependent variable is the sum of the responses of all combined observations, then under the Poisson assumption the distribution remains the same but we have varying `exposure` given by the number of individuals that are represented by one aggregated observation.\n",
    "\n",
    "The parameter estimates and covariance of parameters are the same with the original data, but log-likelihood, deviance and Pearson chi-squared differ"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs_sum ~ rate_marriage + age + yrs_married\",\n",
    "    data=df_a,\n",
    "    family=sm.families.Poisson(),\n",
    "    exposure=np.asarray(df_a[\"affairs_count\"]),\n",
    ")\n",
    "res_e = glm.fit()\n",
    "print(res_e.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e.pearson_chi2 / res_e.df_resid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### using var_weights\n",
    "\n",
    "We can also use the mean of all combined values of the dependent variable. In this case the variance will be related to the inverse of the total exposure reflected by one combined observation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs_mean ~ rate_marriage + age + yrs_married\",\n",
    "    data=df_a,\n",
    "    family=sm.families.Poisson(),\n",
    "    var_weights=np.asarray(df_a[\"affairs_count\"]),\n",
    ")\n",
    "res_a = glm.fit()\n",
    "print(res_a.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Comparison\n",
    "\n",
    "We saw in the summary prints above that ``params`` and ``cov_params`` with associated Wald inference agree across versions. We summarize this in the following comparing individual results attributes across versions.\n",
    "\n",
    "Parameter estimates `params`, standard errors of the parameters `bse` and `pvalues` of the parameters for the tests that the parameters are zeros all agree. However, the likelihood and goodness-of-fit statistics, `llf`, `deviance` and `pearson_chi2` only partially agree. Specifically, the aggregated version do not agree with the results using the original data.\n",
    "\n",
    "**Warning**: The behavior of `llf`, `deviance` and `pearson_chi2` might still change in future versions.\n",
    "\n",
    "Both the sum and average of the response variable for unique values of the explanatory variables have a proper likelihood interpretation. However, this interpretation is not reflected in these three statistics. Computationally this might be due to missing adjustments when aggregated data is used. However, theoretically we can think in these cases, especially for `var_weights` of the misspecified case when likelihood analysis is inappropriate and the results should be interpreted as quasi-likelihood estimates. There is an ambiguity in the definition of ``var_weights`` because they can be used for averages with correctly specified likelihood as well as for variance adjustments in the quasi-likelihood case. We are currently not trying to match the likelihood specification. However, in the next section we show that likelihood ratio type tests still produce the same result for all aggregation versions when we assume that the underlying model is correctly specified."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "results_all = [res_o, res_f, res_e, res_a]\n",
    "names = \"res_o res_f res_e res_a\".split()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "pd.concat([r.params for r in results_all], axis=1, keys=names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "pd.concat([r.bse for r in results_all], axis=1, keys=names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "pd.concat([r.pvalues for r in results_all], axis=1, keys=names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "pd.DataFrame(\n",
    "    np.column_stack([[r.llf, r.deviance, r.pearson_chi2] for r in results_all]),\n",
    "    columns=names,\n",
    "    index=[\"llf\", \"deviance\", \"pearson chi2\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Likelihood Ratio type tests\n",
    "\n",
    "We saw above that likelihood and related statistics do not agree between the aggregated and original, individual data. We illustrate in the following that likelihood ratio test and difference in deviance agree across versions, however Pearson chi-squared does not.\n",
    "\n",
    "As before: This is not sufficiently clear yet and could change.\n",
    "\n",
    "As a test case we drop the `age` variable and compute the likelihood ratio type statistics as difference between reduced or constrained and full or unconstrained model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### original observations and frequency weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs ~ rate_marriage + yrs_married\", data=data, family=sm.families.Poisson()\n",
    ")\n",
    "res_o2 = glm.fit()\n",
    "# print(res_f2.summary())\n",
    "res_o2.pearson_chi2 - res_o.pearson_chi2, res_o2.deviance - res_o.deviance, res_o2.llf - res_o.llf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs ~ rate_marriage + yrs_married\",\n",
    "    data=dc,\n",
    "    family=sm.families.Poisson(),\n",
    "    freq_weights=np.asarray(dc[\"freq\"]),\n",
    ")\n",
    "res_f2 = glm.fit()\n",
    "# print(res_f2.summary())\n",
    "res_f2.pearson_chi2 - res_f.pearson_chi2, res_f2.deviance - res_f.deviance, res_f2.llf - res_f.llf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### aggregated data: ``exposure`` and ``var_weights``\n",
    "\n",
    "Note: LR test agrees with original observations, ``pearson_chi2`` differs and has the wrong sign."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs_sum ~ rate_marriage + yrs_married\",\n",
    "    data=df_a,\n",
    "    family=sm.families.Poisson(),\n",
    "    exposure=np.asarray(df_a[\"affairs_count\"]),\n",
    ")\n",
    "res_e2 = glm.fit()\n",
    "res_e2.pearson_chi2 - res_e.pearson_chi2, res_e2.deviance - res_e.deviance, res_e2.llf - res_e.llf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "glm = smf.glm(\n",
    "    \"affairs_mean ~ rate_marriage + yrs_married\",\n",
    "    data=df_a,\n",
    "    family=sm.families.Poisson(),\n",
    "    var_weights=np.asarray(df_a[\"affairs_count\"]),\n",
    ")\n",
    "res_a2 = glm.fit()\n",
    "res_a2.pearson_chi2 - res_a.pearson_chi2, res_a2.deviance - res_a.deviance, res_a2.llf - res_a.llf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Investigating Pearson chi-square statistic\n",
    "\n",
    "First, we do some sanity checks that there are no basic bugs in the computation of `pearson_chi2` and `resid_pearson`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e2.pearson_chi2, res_e.pearson_chi2, (res_e2.resid_pearson ** 2).sum(), (\n",
    "    res_e.resid_pearson ** 2\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e._results.resid_response.mean(), res_e.model.family.variance(res_e.mu)[\n",
    "    :5\n",
    "], res_e.mu[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(res_e._results.resid_response ** 2 / res_e.model.family.variance(res_e.mu)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e2._results.resid_response.mean(), res_e2.model.family.variance(res_e2.mu)[\n",
    "    :5\n",
    "], res_e2.mu[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(res_e2._results.resid_response ** 2 / res_e2.model.family.variance(res_e2.mu)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(res_e2._results.resid_response ** 2).sum(), (res_e._results.resid_response ** 2).sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One possible reason for the incorrect sign is that we are subtracting quadratic terms that are divided by different denominators. In some related cases, the recommendation in the literature is to use a common denominator. We can compare pearson chi-squared statistic using the same variance assumption in the full and reduced model. \n",
    "\n",
    "In this case we obtain the same pearson chi2 scaled difference between reduced and full model across all versions. (Issue [#3616](https://github.com/statsmodels/statsmodels/issues/3616) is intended to track this further.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_e2._results.resid_response ** 2 - res_e._results.resid_response ** 2)\n",
    "    / res_e2.model.family.variance(res_e2.mu)\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_a2._results.resid_response ** 2 - res_a._results.resid_response ** 2)\n",
    "    / res_a2.model.family.variance(res_a2.mu)\n",
    "    * res_a2.model.var_weights\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_f2._results.resid_response ** 2 - res_f._results.resid_response ** 2)\n",
    "    / res_f2.model.family.variance(res_f2.mu)\n",
    "    * res_f2.model.freq_weights\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_o2._results.resid_response ** 2 - res_o._results.resid_response ** 2)\n",
    "    / res_o2.model.family.variance(res_o2.mu)\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Remainder\n",
    "\n",
    "The remainder of the notebook just contains some additional checks and can be ignored."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "np.exp(res_e2.model.exposure)[:5], np.asarray(df_a[\"affairs_count\"])[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e2.resid_pearson.sum() - res_e.resid_pearson.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e2.mu[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_a2.pearson_chi2, res_a.pearson_chi2, res_a2.resid_pearson.sum(), res_a.resid_pearson.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_a2._results.resid_response ** 2)\n",
    "    / res_a2.model.family.variance(res_a2.mu)\n",
    "    * res_a2.model.var_weights\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_a._results.resid_response ** 2)\n",
    "    / res_a.model.family.variance(res_a.mu)\n",
    "    * res_a.model.var_weights\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(\n",
    "    (res_a._results.resid_response ** 2)\n",
    "    / res_a.model.family.variance(res_a2.mu)\n",
    "    * res_a.model.var_weights\n",
    ").sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_e.model.endog[:5], res_e2.model.endog[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_a.model.endog[:5], res_a2.model.endog[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_a2.model.endog[:5] * np.exp(res_e2.model.exposure)[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_a2.model.endog[:5] * res_a2.model.var_weights[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "\n",
    "stats.chi2.sf(27.19530754604785, 1), stats.chi2.sf(29.083798806764687, 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "res_o.pvalues"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "print(res_e2.summary())\n",
    "print(res_e.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "print(res_f2.summary())\n",
    "print(res_f.summary())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
