Skip to content

Commit c43d7ad

Browse files
authored
Merge pull request #795 from bashtage/lm71-fix-panel-clusters
BUG: Do not let the order of the clusters change the PanelOLS degrees…
2 parents 27aec1d + 3a937a7 commit c43d7ad

3 files changed

Lines changed: 327 additions & 8 deletions

File tree

‎linearmodels/panel/model.py‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,11 @@ def _setup_clusters(
10261026
# https://github.com/pandas-dev/pandas-stubs/issues/111
10271027
formatted_clusters.dataframe[col] = cat.codes.astype(np.int64)
10281028
clusters_frame = formatted_clusters.dataframe
1029+
if self._singleton_index is not None:
1030+
# The clusters have a value for each observation that is not missing.
1031+
# The singletons are dropped from the data of the model, and so are
1032+
# the clusters that are made from it below, which do not need this
1033+
clusters_frame = clusters_frame.loc[~self._singleton_index]
10291034

10301035
cluster_entity = bool(cov_config_upd.pop("cluster_entity", False))
10311036
if cluster_entity:
@@ -1048,8 +1053,6 @@ def _setup_clusters(
10481053
clusters_frame[name] = group_ids
10491054
else:
10501055
clusters_frame = DataFrame(group_ids)
1051-
if self._singleton_index is not None and clusters_frame is not None:
1052-
clusters_frame = clusters_frame.loc[~self._singleton_index]
10531056

10541057
if clusters_frame is not None:
10551058
cov_config_upd["clusters"] = np.asarray(clusters_frame)
@@ -2089,17 +2092,22 @@ def _is_effect_nested(
20892092
effects: linearmodels.typing.NumericArray,
20902093
clusters: linearmodels.typing.NumericArray,
20912094
) -> bool:
2092-
"""Determine whether an effect is nested by the covariance clusters"""
2093-
is_nested = np.zeros(effects.shape[1], dtype=bool)
2094-
for i, e in enumerate(effects.T):
2095+
"""
2096+
Determine whether the effects are nested by the covariance clusters
2097+
2098+
An effect is nested if each of its groups is in one group of every one of
2099+
the cluster variables, so that the result does not depend on their order.
2100+
"""
2101+
for e in effects.T:
20952102
_e = (e - e.min()).astype(np.int64)
20962103
e_count = len(np.unique(_e))
20972104
for c in clusters.T:
20982105
_c = (c - c.min()).astype(np.int64)
20992106
cmax = _c.max()
21002107
ec = _e * (cmax + 1) + _c
2101-
is_nested[i] = len(np.unique(ec)) == e_count
2102-
return bool(np.all(is_nested))
2108+
if len(np.unique(ec)) != e_count:
2109+
return False
2110+
return True
21032111

21042112
def _determine_df_adjustment(
21052113
self,
@@ -2180,7 +2188,9 @@ def fit(
21802188
of freedom adjustment is automatically handled. This is useful
21812189
since clustered standard errors that are clustered using the same
21822190
variable as an effect do not require degree of freedom correction
2183-
while other estimators such as the unadjusted covariance do.
2191+
while other estimators such as the unadjusted covariance do. With
2192+
two cluster variables, the effect has to be nested in both of them,
2193+
which means that each of its groups is in one group of each variable.
21842194
count_effects : bool
21852195
Flag indicating that the covariance estimator should be adjusted
21862196
to account for the estimation of effects in the model. Only used
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
"""
2+
The degrees of freedom of the clustered covariance of PanelOLS with one effect
3+
4+
The covariance does not count the degrees of freedom of an effect that is nested in
5+
the clusters, since an effect with the same groups as a cluster (e.g., entity effects
6+
and clustering by entity) is purged from the scores of the cluster. With several
7+
cluster variables, e.g., two-way clustering, the effect has to be nested in all of them,
8+
as in AbsorbingLS. It was nested if it was in the last cluster variable only, so that
9+
the standard errors changed with the order of the cluster variables.
10+
11+
The reference is the covariance of the regression on the data from which the effect is
12+
removed, written out in NumPy.
13+
"""
14+
15+
import numpy as np
16+
from numpy.testing import assert_allclose
17+
import pandas as pd
18+
import pytest
19+
20+
from linearmodels.panel import PanelOLS
21+
22+
23+
def make_data(unbalanced, seed=3, nentity=30, nperiod=8):
24+
"""A panel with entities that are nested in industries"""
25+
rg = np.random.default_rng(seed)
26+
index = pd.MultiIndex.from_product(
27+
[np.arange(nentity), np.arange(nperiod)], names=["id", "year"]
28+
)
29+
entity, period = index.codes
30+
x = rg.standard_normal((index.shape[0], 2))
31+
effect = rg.standard_normal(nentity)[entity]
32+
shock = (1 + np.abs(x[:, 0])) * rg.standard_normal(index.shape[0])
33+
data = pd.DataFrame(
34+
{
35+
"y": x @ [0.5, -0.3] + effect + shock,
36+
"x1": x[:, 0],
37+
"x2": x[:, 1],
38+
"entity": entity,
39+
"time": period,
40+
"industry": entity // 5,
41+
"group": (entity + period) % 4,
42+
},
43+
index=index,
44+
)
45+
if unbalanced:
46+
keep = rg.random((nentity, nperiod)) > 0.3
47+
for i in range(nentity):
48+
keep[i, rg.choice(nperiod, 3, replace=False)] = True
49+
data = data.loc[keep.ravel()]
50+
return data
51+
52+
53+
@pytest.fixture(params=[False, True], ids=["balanced", "unbalanced"], scope="module")
54+
def data(request):
55+
return make_data(request.param)
56+
57+
58+
EFFECTS = {
59+
"entity": {"entity_effects": True},
60+
"time": {"time_effects": True},
61+
"group": {"other_effects": ("group",)},
62+
}
63+
PAIRS = [
64+
("entity", "time"),
65+
("industry", "time"),
66+
("industry", "entity"),
67+
("group", "time"),
68+
("entity", "group"),
69+
]
70+
71+
72+
def build(data, effect):
73+
options = dict(EFFECTS[effect])
74+
if "other_effects" in options:
75+
options["other_effects"] = data[list(options["other_effects"])]
76+
return PanelOLS(data["y"], data[["x1", "x2"]], **options)
77+
78+
79+
def sum_of_scores(scores, groups):
80+
total = 0.0
81+
for key in np.unique(groups):
82+
score = scores[groups == key].sum(0)
83+
total = total + np.outer(score, score)
84+
return total
85+
86+
87+
def clustered_covariance(data, effect, clusters, count_effects):
88+
"""Debiased covariance of the regression on the data without the effect"""
89+
groups = data[effect].to_numpy()
90+
x = data[["x1", "x2"]] - data[["x1", "x2"]].groupby(groups).transform("mean")
91+
y = data["y"] - data["y"].groupby(groups).transform("mean")
92+
x, y = x.to_numpy(), y.to_numpy()
93+
resid = y - x @ np.linalg.lstsq(x, y, rcond=None)[0]
94+
scores = x * resid[:, None]
95+
labels = [data[c].to_numpy() for c in clusters]
96+
meat = sum_of_scores(scores, labels[0])
97+
if len(labels) == 2:
98+
pairs = pd.factorize(pd.Series(list(zip(*labels, strict=True))))[0]
99+
meat = meat + sum_of_scores(scores, labels[1]) - sum_of_scores(scores, pairs)
100+
nobs, nvar = x.shape
101+
neffects = np.unique(groups).shape[0] if count_effects else 0
102+
bread = np.linalg.inv(x.T @ x)
103+
return bread @ meat @ bread * nobs / (nobs - neffects - nvar)
104+
105+
106+
def is_nested(data, effect, clusters):
107+
"""The groups of the effect are in a single group of every cluster variable"""
108+
by_effect = data.groupby(effect)
109+
return all(by_effect[c].nunique().max() == 1 for c in clusters)
110+
111+
112+
@pytest.mark.parametrize("pair", PAIRS)
113+
@pytest.mark.parametrize("effect", list(EFFECTS))
114+
def test_clustered_covariance_against_hand_computation(data, effect, pair):
115+
mod = build(data, effect)
116+
expected = {}
117+
for clusters in (list(pair), list(reversed(pair))):
118+
res = mod.fit(cov_type="clustered", clusters=data[clusters])
119+
expected = clustered_covariance(
120+
data, effect, clusters, count_effects=not is_nested(data, effect, clusters)
121+
)
122+
assert_allclose(res.cov.to_numpy(), expected, rtol=1e-8)
123+
124+
125+
@pytest.mark.parametrize("pair", PAIRS)
126+
@pytest.mark.parametrize("effect", list(EFFECTS))
127+
def test_order_of_the_clusters_does_not_matter(data, effect, pair):
128+
mod = build(data, effect)
129+
forward = mod.fit(cov_type="clustered", clusters=data[list(pair)])
130+
backward = mod.fit(cov_type="clustered", clusters=data[list(reversed(pair))])
131+
assert_allclose(forward.cov, backward.cov)
132+
133+
134+
@pytest.mark.parametrize("effect", ["entity", "time"])
135+
def test_cluster_entity_and_cluster_time(data, effect):
136+
# An effect that is nested in the clusters by entity or by time only is counted
137+
mod = build(data, effect)
138+
res = mod.fit(cov_type="clustered", cluster_entity=True, cluster_time=True)
139+
expected = clustered_covariance(
140+
data, effect, ["entity", "time"], count_effects=True
141+
)
142+
assert_allclose(res.cov.to_numpy(), expected, rtol=1e-8)
143+
one_way = mod.fit(
144+
cov_type="clustered",
145+
cluster_entity=effect == "entity",
146+
cluster_time=effect == "time",
147+
)
148+
expected = clustered_covariance(data, effect, [effect], count_effects=False)
149+
assert_allclose(one_way.cov.to_numpy(), expected, rtol=1e-8)
150+
151+
152+
def test_nested_in_all_clusters_does_not_count_the_effects(data):
153+
# Entities are nested in industries: both cluster variables nest the entity effects
154+
mod = build(data, "entity")
155+
res = mod.fit(cov_type="clustered", clusters=data[["industry", "entity"]])
156+
counted = mod.fit(
157+
cov_type="clustered",
158+
clusters=data[["industry", "entity"]],
159+
auto_df=False,
160+
count_effects=True,
161+
)
162+
not_counted = mod.fit(
163+
cov_type="clustered",
164+
clusters=data[["industry", "entity"]],
165+
auto_df=False,
166+
count_effects=False,
167+
)
168+
assert_allclose(res.cov, not_counted.cov)
169+
assert not np.allclose(res.cov, counted.cov)
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
"""
2+
PanelOLS with singletons=False and the clusters of the entities or the time periods
3+
4+
The singleton observations are dropped from the data of the model, and cluster_entity and
5+
cluster_time (which are made from the data of the model) have to have the observations
6+
that remain. They raised "IndexError: Boolean index has wrong length", since the mask of
7+
the singletons, which has a value for each observation before they were dropped, was also
8+
applied to the clusters that were made after. The results have to be those of the model
9+
estimated from the data without the singleton observations.
10+
"""
11+
12+
import numpy as np
13+
from numpy.testing import assert_allclose
14+
import pandas as pd
15+
import pytest
16+
17+
from linearmodels.panel import PanelOLS
18+
from linearmodels.shared.exceptions import MissingValueWarning, SingletonWarning
19+
20+
NENTITY = 30
21+
NPERIOD = 6
22+
23+
24+
def make_data(seed=0, nsingleton=3):
25+
"""A panel in which the first entities have a single observation"""
26+
rg = np.random.default_rng(seed)
27+
index = pd.MultiIndex.from_product(
28+
[np.arange(NENTITY), np.arange(NPERIOD)], names=["entity", "time"]
29+
)
30+
entity = index.codes[0]
31+
x = rg.standard_normal((index.shape[0], 2))
32+
effect = rg.standard_normal(NENTITY)[entity]
33+
shock = (1 + np.abs(x[:, 0])) * rg.standard_normal(index.shape[0])
34+
data = pd.DataFrame(
35+
{
36+
"y": x @ [0.5, -0.3] + effect + shock,
37+
"x1": x[:, 0],
38+
"x2": x[:, 1],
39+
"w": rg.chisquare(4, index.shape[0]) / 4 + 0.2,
40+
"group": entity // 5,
41+
},
42+
index=index,
43+
)
44+
# Entities 3, 7, ... keep a single observation
45+
keep = np.ones(index.shape[0], dtype=bool)
46+
for i in range(nsingleton):
47+
rows = np.flatnonzero(entity == 3 + 4 * i)
48+
keep[rows[1:]] = False
49+
return data.loc[keep]
50+
51+
52+
def drop_singletons(data, effects):
53+
"""Drop the observations that are alone in a group of an effect, repeatedly"""
54+
while True:
55+
alone = np.zeros(data.shape[0], dtype=bool)
56+
for level in effects:
57+
keys = data.index.get_level_values(level)
58+
alone |= data.groupby(keys)["y"].transform("size").to_numpy() == 1
59+
if not alone.any():
60+
return data
61+
data = data.loc[~alone]
62+
63+
64+
COVARIANCES = {
65+
"entity": {"cluster_entity": True},
66+
"time": {"cluster_time": True},
67+
"entity-time": {"cluster_entity": True, "cluster_time": True},
68+
}
69+
EFFECTS = {
70+
"entity": ({"entity_effects": True}, ["entity"]),
71+
"both": ({"entity_effects": True, "time_effects": True}, ["entity", "time"]),
72+
}
73+
74+
75+
def compare(res, expected):
76+
assert res.nobs == expected.nobs
77+
assert_allclose(res.params, expected.params)
78+
assert_allclose(res.cov, expected.cov)
79+
assert_allclose(res.std_errors, expected.std_errors)
80+
assert_allclose(res.f_statistic_robust.stat, expected.f_statistic_robust.stat)
81+
82+
83+
@pytest.mark.parametrize("weighted", [False, True], ids=["unweighted", "weighted"])
84+
@pytest.mark.parametrize("clustering", list(COVARIANCES))
85+
@pytest.mark.parametrize("effect", list(EFFECTS))
86+
def test_singleton_observations_with_clusters_of_the_model(
87+
effect, clustering, weighted
88+
):
89+
data = make_data()
90+
options, levels = EFFECTS[effect]
91+
weights = data["w"] if weighted else None
92+
with pytest.warns(SingletonWarning):
93+
mod = PanelOLS(
94+
data["y"], data[["x1", "x2"]], weights=weights, singletons=False, **options
95+
)
96+
res = mod.fit(cov_type="clustered", **COVARIANCES[clustering])
97+
kept = drop_singletons(data, levels)
98+
assert kept.shape[0] < data.shape[0]
99+
manual_weights = kept["w"] if weighted else None
100+
expected = PanelOLS(
101+
kept["y"], kept[["x1", "x2"]], weights=manual_weights, **options
102+
).fit(cov_type="clustered", **COVARIANCES[clustering])
103+
compare(res, expected)
104+
105+
106+
@pytest.mark.parametrize("clustering", ["entity", "time"])
107+
def test_singleton_observations_with_clusters_and_the_clusters_of_the_model(clustering):
108+
# The clusters that are given have a value for each observation of the data, and
109+
# are two-way clusters together with the cluster of the entities or of the periods
110+
data = make_data()
111+
with pytest.warns(SingletonWarning):
112+
mod = PanelOLS(
113+
data["y"], data[["x1", "x2"]], singletons=False, entity_effects=True
114+
)
115+
res = mod.fit(
116+
cov_type="clustered", clusters=data[["group"]], **COVARIANCES[clustering]
117+
)
118+
kept = drop_singletons(data, ["entity"])
119+
expected = PanelOLS(kept["y"], kept[["x1", "x2"]], entity_effects=True).fit(
120+
cov_type="clustered", clusters=kept[["group"]], **COVARIANCES[clustering]
121+
)
122+
compare(res, expected)
123+
124+
125+
def test_singleton_observations_with_missing_values_and_clusters():
126+
# The missing observations are dropped before the singletons, and the singletons
127+
# are the observations that remain alone
128+
data = make_data()
129+
missing = data.copy()
130+
missing.iloc[[5, 6, 40, 41, 42, 90], missing.columns.get_loc("x1")] = np.nan
131+
with pytest.warns((SingletonWarning, MissingValueWarning)):
132+
mod = PanelOLS(
133+
missing["y"], missing[["x1", "x2"]], singletons=False, entity_effects=True
134+
)
135+
res = mod.fit(cov_type="clustered", cluster_entity=True, cluster_time=True)
136+
kept = drop_singletons(missing.dropna(subset=["x1"]), ["entity"])
137+
expected = PanelOLS(kept["y"], kept[["x1", "x2"]], entity_effects=True).fit(
138+
cov_type="clustered", cluster_entity=True, cluster_time=True
139+
)
140+
compare(res, expected)

0 commit comments

Comments
 (0)