shiftshare 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
shiftshare/__init__.py ADDED
@@ -0,0 +1,114 @@
1
+ """shiftshare: regional economic analysis on region x sector employment matrices.
2
+
3
+ Location quotients (SLQ, CILQ, FLQ, AFLQ) and LQ regionalisation of input-output
4
+ coefficients; shift-share decompositions (Dunn 1960, Esteban-Marquillas 1972, Arcelus 1984,
5
+ dynamic Barff & Knight 1988); Krugman specialisation, Hoover localisation and
6
+ specialisation coefficients, locational Gini and Herfindahl; the Ellison-Glaeser (1997)
7
+ agglomeration and coagglomeration indices; and economic base multipliers by the
8
+ assumption, location quotient and minimum requirements methods.
9
+ """
10
+
11
+ from ._common import EmploymentTable, ShiftShareError, label_records
12
+ from ._version import __version__
13
+ from .agglomeration import (
14
+ EGResult,
15
+ coagglomeration,
16
+ ellison_glaeser,
17
+ plant_herfindahl,
18
+ raw_concentration,
19
+ )
20
+ from .analysis import decompose, decompose_dynamic, profile
21
+ from .base import (
22
+ BaseResult,
23
+ assumption_method,
24
+ base_multiplier,
25
+ lq_method,
26
+ minimum_requirements,
27
+ )
28
+ from .decomposition import (
29
+ ALLOCATION_TYPES,
30
+ ArcelusResult,
31
+ DynamicResult,
32
+ EstebanMarquillasResult,
33
+ ShiftShareResult,
34
+ arcelus,
35
+ classic,
36
+ dynamic,
37
+ esteban_marquillas,
38
+ growth_rates,
39
+ )
40
+ from .io import read_table, read_vector, write_csv, write_json
41
+ from .quotients import (
42
+ aflq,
43
+ cross_industry_lq,
44
+ flegg_lambda,
45
+ flq,
46
+ location_quotient,
47
+ regional_employment,
48
+ regionalize,
49
+ )
50
+ from .specialization import (
51
+ LocalizationCurve,
52
+ coefficient_of_localization,
53
+ coefficient_of_specialization,
54
+ herfindahl,
55
+ krugman_index,
56
+ krugman_pairwise,
57
+ localization_curve,
58
+ sector_shares,
59
+ )
60
+
61
+ __all__ = [
62
+ "__version__",
63
+ "ShiftShareError",
64
+ "EmploymentTable",
65
+ "label_records",
66
+ # location quotients
67
+ "location_quotient",
68
+ "cross_industry_lq",
69
+ "flegg_lambda",
70
+ "flq",
71
+ "aflq",
72
+ "regionalize",
73
+ "regional_employment",
74
+ # shift-share
75
+ "classic",
76
+ "esteban_marquillas",
77
+ "arcelus",
78
+ "dynamic",
79
+ "growth_rates",
80
+ "ShiftShareResult",
81
+ "EstebanMarquillasResult",
82
+ "ArcelusResult",
83
+ "DynamicResult",
84
+ "ALLOCATION_TYPES",
85
+ # specialisation and localisation
86
+ "sector_shares",
87
+ "krugman_index",
88
+ "krugman_pairwise",
89
+ "coefficient_of_specialization",
90
+ "coefficient_of_localization",
91
+ "localization_curve",
92
+ "LocalizationCurve",
93
+ "herfindahl",
94
+ # agglomeration
95
+ "plant_herfindahl",
96
+ "raw_concentration",
97
+ "ellison_glaeser",
98
+ "coagglomeration",
99
+ "EGResult",
100
+ # economic base
101
+ "assumption_method",
102
+ "lq_method",
103
+ "minimum_requirements",
104
+ "base_multiplier",
105
+ "BaseResult",
106
+ # summaries and I/O
107
+ "profile",
108
+ "decompose",
109
+ "decompose_dynamic",
110
+ "read_table",
111
+ "read_vector",
112
+ "write_csv",
113
+ "write_json",
114
+ ]
shiftshare/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m shiftshare``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
shiftshare/_common.py ADDED
@@ -0,0 +1,265 @@
1
+ """Shared helpers: input validation and the labelled region x sector employment table."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union
7
+
8
+ import numpy as np
9
+
10
+ __all__ = [
11
+ "ShiftShareError",
12
+ "EmploymentTable",
13
+ "as_matrix",
14
+ "as_vector",
15
+ "safe_div",
16
+ "label_records",
17
+ ]
18
+
19
+
20
+ class ShiftShareError(ValueError):
21
+ """Raised for invalid inputs (shapes, negative employment, bad parameters)."""
22
+
23
+
24
+ def safe_div(num: Any, den: Any) -> np.ndarray:
25
+ """Element-wise ``num / den`` with ``nan`` where ``den == 0``."""
26
+ n = np.asarray(num, dtype=float)
27
+ d = np.asarray(den, dtype=float)
28
+ shape = np.broadcast_shapes(n.shape, d.shape)
29
+ out = np.full(shape, np.nan)
30
+ np.divide(n, d, out=out, where=np.broadcast_to(d != 0, shape))
31
+ return out
32
+
33
+
34
+ def _check_values(arr: np.ndarray, name: str) -> None:
35
+ if arr.size == 0:
36
+ raise ShiftShareError(f"{name} is empty")
37
+ if not np.all(np.isfinite(arr)):
38
+ raise ShiftShareError(f"{name} contains NaN or infinite values")
39
+ if (arr < 0).any():
40
+ raise ShiftShareError(f"{name} contains negative employment")
41
+
42
+
43
+ def as_matrix(data: Any, name: str = "employment") -> np.ndarray:
44
+ """Return a 2-D float ``(regions, sectors)`` copy of *data*.
45
+
46
+ Accepts an :class:`EmploymentTable`, a NumPy array or nested sequences. A 1-D input is
47
+ treated as a single region. Values must be finite and non-negative.
48
+ """
49
+ if isinstance(data, EmploymentTable):
50
+ arr = data.values.astype(float, copy=True)
51
+ else:
52
+ try:
53
+ arr = np.array(data, dtype=float)
54
+ except (TypeError, ValueError):
55
+ raise ShiftShareError(f"{name} must be numeric") from None
56
+ if arr.ndim == 1:
57
+ arr = arr.reshape(1, -1)
58
+ if arr.ndim != 2:
59
+ raise ShiftShareError(f"{name} must be a 2-D regions x sectors array, got {arr.ndim}-D")
60
+ _check_values(arr, name)
61
+ return arr
62
+
63
+
64
+ def as_vector(data: Any, size: Optional[int] = None, name: str = "vector") -> np.ndarray:
65
+ """Return a 1-D float copy of *data*, optionally checking its length."""
66
+ try:
67
+ arr = np.array(data, dtype=float).ravel()
68
+ except (TypeError, ValueError):
69
+ raise ShiftShareError(f"{name} must be numeric") from None
70
+ if size is not None and arr.size != size:
71
+ raise ShiftShareError(f"{name} has {arr.size} values, expected {size}")
72
+ _check_values(arr, name)
73
+ return arr
74
+
75
+
76
+ def label_records(
77
+ array: Any,
78
+ regions: Sequence[str],
79
+ sectors: Sequence[str],
80
+ value_name: str = "value",
81
+ ) -> List[Dict[str, Any]]:
82
+ """Flatten a ``(regions, sectors)`` array into long records ``{region, sector, value}``."""
83
+ arr = np.asarray(array, dtype=float)
84
+ if arr.shape != (len(regions), len(sectors)):
85
+ raise ShiftShareError(
86
+ f"array shape {arr.shape} does not match {len(regions)} regions x "
87
+ f"{len(sectors)} sectors"
88
+ )
89
+ return [
90
+ {"region": r, "sector": s, value_name: float(arr[i, j])}
91
+ for i, r in enumerate(regions)
92
+ for j, s in enumerate(sectors)
93
+ ]
94
+
95
+
96
+ def _default_labels(prefix: str, n: int) -> List[str]:
97
+ return [f"{prefix}{k + 1}" for k in range(n)]
98
+
99
+
100
+ @dataclass
101
+ class EmploymentTable:
102
+ """A labelled ``regions x sectors`` employment (or output, establishments) matrix.
103
+
104
+ ``values[r, s]`` is employment of sector ``s`` in region ``r``. Every function in the
105
+ package also accepts a bare NumPy array; the table adds labels for records and CSV/JSON.
106
+ """
107
+
108
+ values: np.ndarray
109
+ regions: List[str] = field(default_factory=list)
110
+ sectors: List[str] = field(default_factory=list)
111
+
112
+ def __post_init__(self) -> None:
113
+ self.values = as_matrix(self.values, "values")
114
+ nr, ns = self.values.shape
115
+ self.regions = [str(r) for r in self.regions] or _default_labels("R", nr)
116
+ self.sectors = [str(s) for s in self.sectors] or _default_labels("S", ns)
117
+ if len(self.regions) != nr or len(self.sectors) != ns:
118
+ raise ShiftShareError(
119
+ f"labels ({len(self.regions)} regions, {len(self.sectors)} sectors) do not "
120
+ f"match values shape {self.values.shape}"
121
+ )
122
+ if len(set(self.regions)) != nr or len(set(self.sectors)) != ns:
123
+ raise ShiftShareError("region and sector labels must be unique")
124
+
125
+ # construction -----------------------------------------------------------------------
126
+ @classmethod
127
+ def from_records(
128
+ cls,
129
+ records: Iterable[Mapping[str, Any]],
130
+ region: str = "region",
131
+ sector: str = "sector",
132
+ value: str = "employment",
133
+ ) -> EmploymentTable:
134
+ """Build a table from long records; missing region-sector pairs are zero and
135
+ duplicate pairs are summed."""
136
+ rows = list(records)
137
+ if not rows:
138
+ raise ShiftShareError("no records")
139
+ regions: List[str] = []
140
+ sectors: List[str] = []
141
+ for rec in rows:
142
+ try:
143
+ r, s = str(rec[region]), str(rec[sector])
144
+ except KeyError as exc:
145
+ raise ShiftShareError(f"record lacks field {exc}") from None
146
+ if r not in regions:
147
+ regions.append(r)
148
+ if s not in sectors:
149
+ sectors.append(s)
150
+ ri = {r: k for k, r in enumerate(regions)}
151
+ si = {s: k for k, s in enumerate(sectors)}
152
+ vals = np.zeros((len(regions), len(sectors)))
153
+ for rec in rows:
154
+ raw = rec.get(value)
155
+ try:
156
+ v = float(raw) if raw not in (None, "") else 0.0
157
+ except (TypeError, ValueError):
158
+ raise ShiftShareError(f"non-numeric {value!r} value: {raw!r}") from None
159
+ vals[ri[str(rec[region])], si[str(rec[sector])]] += v
160
+ return cls(vals, regions, sectors)
161
+
162
+ @classmethod
163
+ def from_dict(cls, data: Mapping[str, Mapping[str, Any]]) -> EmploymentTable:
164
+ """Build from ``{region: {sector: value}}``; missing sectors are zero."""
165
+ regions = [str(r) for r in data]
166
+ sectors: List[str] = []
167
+ for row in data.values():
168
+ for s in row:
169
+ if str(s) not in sectors:
170
+ sectors.append(str(s))
171
+ vals = np.zeros((len(regions), len(sectors)))
172
+ for i, row in enumerate(data.values()):
173
+ for s, v in row.items():
174
+ vals[i, sectors.index(str(s))] = float(v)
175
+ return cls(vals, regions, sectors)
176
+
177
+ # access -----------------------------------------------------------------------------
178
+ @property
179
+ def shape(self) -> tuple:
180
+ return tuple(self.values.shape)
181
+
182
+ def region_totals(self) -> np.ndarray:
183
+ return np.asarray(self.values.sum(axis=1))
184
+
185
+ def sector_totals(self) -> np.ndarray:
186
+ return np.asarray(self.values.sum(axis=0))
187
+
188
+ def total(self) -> float:
189
+ return float(self.values.sum())
190
+
191
+ def region_index(self, region: Union[int, str]) -> int:
192
+ """Position of *region* given as a label or an integer index."""
193
+ if isinstance(region, (int, np.integer)) and not isinstance(region, bool):
194
+ if not -len(self.regions) <= int(region) < len(self.regions):
195
+ raise ShiftShareError(f"region index {region} out of range")
196
+ return int(region) % len(self.regions)
197
+ if str(region) not in self.regions:
198
+ raise ShiftShareError(f"unknown region {region!r}")
199
+ return self.regions.index(str(region))
200
+
201
+ def sector_index(self, sector: Union[int, str]) -> int:
202
+ """Position of *sector* given as a label or an integer index."""
203
+ if isinstance(sector, (int, np.integer)) and not isinstance(sector, bool):
204
+ if not -len(self.sectors) <= int(sector) < len(self.sectors):
205
+ raise ShiftShareError(f"sector index {sector} out of range")
206
+ return int(sector) % len(self.sectors)
207
+ if str(sector) not in self.sectors:
208
+ raise ShiftShareError(f"unknown sector {sector!r}")
209
+ return self.sectors.index(str(sector))
210
+
211
+ def aligned(self, other: EmploymentTable) -> EmploymentTable:
212
+ """Return *other* reordered to this table's region and sector order.
213
+
214
+ Regions or sectors present in only one table raise an error.
215
+ """
216
+ if set(other.regions) != set(self.regions) or set(other.sectors) != set(self.sectors):
217
+ raise ShiftShareError("tables have different region or sector labels")
218
+ ri = [other.regions.index(r) for r in self.regions]
219
+ si = [other.sectors.index(s) for s in self.sectors]
220
+ return EmploymentTable(other.values[np.ix_(ri, si)], self.regions, self.sectors)
221
+
222
+ def records(self, value_name: str = "employment") -> List[Dict[str, Any]]:
223
+ return label_records(self.values, self.regions, self.sectors, value_name)
224
+
225
+ def label(self, array: Any, value_name: str = "value") -> List[Dict[str, Any]]:
226
+ """Long records for any ``(regions, sectors)`` result array of this table."""
227
+ return label_records(array, self.regions, self.sectors, value_name)
228
+
229
+ def to_dict(self) -> Dict[str, Any]:
230
+ return {
231
+ "regions": list(self.regions),
232
+ "sectors": list(self.sectors),
233
+ "values": self.values.tolist(),
234
+ }
235
+
236
+
237
+ def reference_vector(
238
+ employment: np.ndarray, reference: Optional[Any], name: str = "reference"
239
+ ) -> np.ndarray:
240
+ """National (reference) sector totals: *reference* if given, else the column sums."""
241
+ if reference is None:
242
+ ref = employment.sum(axis=0)
243
+ else:
244
+ ref = as_vector(reference, employment.shape[1], name)
245
+ if ref.sum() <= 0:
246
+ raise ShiftShareError(f"{name} total employment must be positive")
247
+ return np.asarray(ref, dtype=float)
248
+
249
+
250
+ def clean_json(obj: Any) -> Any:
251
+ """Make results JSON-safe: arrays to lists, NaN/inf to ``None``."""
252
+ if isinstance(obj, dict):
253
+ return {str(k): clean_json(v) for k, v in obj.items()}
254
+ if isinstance(obj, (list, tuple)):
255
+ return [clean_json(v) for v in obj]
256
+ if isinstance(obj, np.ndarray):
257
+ return clean_json(obj.tolist())
258
+ if isinstance(obj, (np.bool_, bool)):
259
+ return bool(obj)
260
+ if isinstance(obj, (np.integer,)):
261
+ return int(obj)
262
+ if isinstance(obj, (float, np.floating)):
263
+ v = float(obj)
264
+ return v if np.isfinite(v) else None
265
+ return obj
shiftshare/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,165 @@
1
+ """Ellison-Glaeser agglomeration and coagglomeration indices.
2
+
3
+ Ellison, G. and Glaeser, E.L. (1997) Geographic concentration in U.S. manufacturing
4
+ industries: a dartboard approach. *Journal of Political Economy* 105(5), 889-927.
5
+
6
+ The index nets out the concentration expected from plant lumpiness (the plant Herfindahl
7
+ ``H``) so that ``gamma = 0`` corresponds to plants located at random in proportion to
8
+ aggregate employment. Because ``H`` needs plant-level data, it is always supplied by the
9
+ user: as a number per sector or as lists of plant employment.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Sequence
16
+
17
+ import numpy as np
18
+
19
+ from ._common import ShiftShareError, as_matrix, as_vector
20
+
21
+ __all__ = [
22
+ "plant_herfindahl",
23
+ "raw_concentration",
24
+ "ellison_glaeser",
25
+ "coagglomeration",
26
+ "EGResult",
27
+ ]
28
+
29
+
30
+ def plant_herfindahl(plant_employment: Any) -> float:
31
+ """Plant Herfindahl ``H = sum_k z_k^2`` with ``z_k`` plant ``k``'s share of the
32
+ industry's employment (Ellison & Glaeser 1997)."""
33
+ z = as_vector(plant_employment, name="plant employment")
34
+ if z.sum() <= 0:
35
+ raise ShiftShareError("plant employment must have a positive total")
36
+ z = z / z.sum()
37
+ return float((z**2).sum())
38
+
39
+
40
+ def _aggregate_shares(e: np.ndarray, aggregate: Optional[Any]) -> np.ndarray:
41
+ agg = e.sum(axis=1) if aggregate is None else as_vector(aggregate, e.shape[0], "aggregate")
42
+ if agg.sum() <= 0:
43
+ raise ShiftShareError("aggregate employment must have a positive total")
44
+ return np.asarray(agg / agg.sum())
45
+
46
+
47
+ def raw_concentration(employment: Any, aggregate: Optional[Any] = None) -> np.ndarray:
48
+ """Raw geographic concentration per sector: ``G[i] = sum_r (s[r,i] - x[r])^2``.
49
+
50
+ ``s[r, i]`` is region ``r``'s share of sector ``i`` employment and ``x[r]`` its share of
51
+ aggregate employment (by default the row sums of *employment*; pass *aggregate*, one
52
+ value per region, to use e.g. total manufacturing or all-industry employment).
53
+ """
54
+ e = as_matrix(employment)
55
+ x = _aggregate_shares(e, aggregate)
56
+ tot = e.sum(axis=0)
57
+ s = np.divide(e, tot[None, :], out=np.zeros_like(e), where=tot[None, :] > 0)
58
+ g = ((s - x[:, None]) ** 2).sum(axis=0)
59
+ return np.asarray(np.where(tot > 0, g, np.nan))
60
+
61
+
62
+ def _herfindahls(herfindahl: Any, n: int) -> np.ndarray:
63
+ if isinstance(herfindahl, (list, tuple)) and any(
64
+ isinstance(v, (list, tuple, np.ndarray)) for v in herfindahl
65
+ ):
66
+ if len(herfindahl) != n:
67
+ raise ShiftShareError(f"need plant lists for {n} sectors")
68
+ return np.array([plant_herfindahl(v) for v in herfindahl])
69
+ h = np.array(herfindahl, dtype=float).ravel()
70
+ if h.size == 1:
71
+ h = np.repeat(h, n)
72
+ if h.size != n:
73
+ raise ShiftShareError(f"herfindahl has {h.size} values, expected {n}")
74
+ if np.any(~np.isfinite(h)) or np.any((h < 0) | (h >= 1)):
75
+ raise ShiftShareError("plant Herfindahl values must lie in [0, 1)")
76
+ return h
77
+
78
+
79
+ @dataclass
80
+ class EGResult:
81
+ """Ellison-Glaeser results per sector: ``gamma``, raw concentration ``G``, the plant
82
+ Herfindahl ``H`` and ``sum_x2 = sum_r x[r]^2``."""
83
+
84
+ gamma: np.ndarray
85
+ G: np.ndarray
86
+ H: np.ndarray
87
+ sum_x2: float
88
+
89
+ def records(self, sectors: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
90
+ n = self.gamma.size
91
+ labels = list(sectors) if sectors is not None else [f"S{k + 1}" for k in range(n)]
92
+ if len(labels) != n:
93
+ raise ShiftShareError(f"expected {n} sector labels")
94
+ return [
95
+ {
96
+ "sector": str(s),
97
+ "gamma": float(self.gamma[k]),
98
+ "G": float(self.G[k]),
99
+ "H": float(self.H[k]),
100
+ }
101
+ for k, s in enumerate(labels)
102
+ ]
103
+
104
+
105
+ def ellison_glaeser(employment: Any, herfindahl: Any, aggregate: Optional[Any] = None) -> EGResult:
106
+ """Ellison-Glaeser agglomeration index per sector.
107
+
108
+ ``gamma[i] = (G[i] - (1 - sum_r x_r^2) H[i]) / ((1 - sum_r x_r^2)(1 - H[i]))``
109
+
110
+ *herfindahl* is the plant Herfindahl per sector: a number, one number per sector, or
111
+ one list of plant employment per sector. No interpretation thresholds are applied.
112
+
113
+ Source: Ellison, G. and Glaeser, E.L. (1997) *Journal of Political Economy* 105(5),
114
+ 889-927.
115
+ """
116
+ e = as_matrix(employment)
117
+ x = _aggregate_shares(e, aggregate)
118
+ h = _herfindahls(herfindahl, e.shape[1])
119
+ g = raw_concentration(e, aggregate)
120
+ sx2 = float((x**2).sum())
121
+ if sx2 >= 1.0:
122
+ raise ShiftShareError("need at least two regions with aggregate employment")
123
+ gamma = (g - (1.0 - sx2) * h) / ((1.0 - sx2) * (1.0 - h))
124
+ return EGResult(np.asarray(gamma), g, h, sx2)
125
+
126
+
127
+ def coagglomeration(
128
+ employment: Any,
129
+ sectors: Sequence[int],
130
+ herfindahl: Any,
131
+ aggregate: Optional[Any] = None,
132
+ ) -> float:
133
+ """Ellison-Glaeser coagglomeration index of a group of sectors.
134
+
135
+ ``gamma_c = [G / (1 - sum x^2) - H - sum_j gamma_j w_j^2 (1 - H_j)] / (1 - sum_j w_j^2)``
136
+
137
+ where ``G`` is the raw concentration of the group's combined employment, ``w_j`` each
138
+ sector's share of group employment, ``H = sum_j w_j^2 H_j`` the group plant Herfindahl
139
+ and ``gamma_j`` the individual indices. *herfindahl* gives ``H_j`` for the sectors of
140
+ *employment* (as in :func:`ellison_glaeser`).
141
+
142
+ Source: Ellison, G. and Glaeser, E.L. (1997) *Journal of Political Economy* 105(5),
143
+ 889-927.
144
+ """
145
+ e = as_matrix(employment)
146
+ idx = [int(k) for k in sectors]
147
+ if len(set(idx)) < 2:
148
+ raise ShiftShareError("coagglomeration needs at least two distinct sectors")
149
+ for k in idx:
150
+ if not 0 <= k < e.shape[1]:
151
+ raise ShiftShareError(f"sector index {k} out of range")
152
+ single = ellison_glaeser(e, herfindahl, aggregate)
153
+ sub = e[:, idx]
154
+ w = sub.sum(axis=0) / sub.sum()
155
+ h_j = single.H[idx]
156
+ gam_j = single.gamma[idx]
157
+ group_g = float(
158
+ raw_concentration(
159
+ sub.sum(axis=1, keepdims=True), aggregate if aggregate is not None else e.sum(axis=1)
160
+ )[0]
161
+ )
162
+ h = float((w**2 * h_j).sum())
163
+ sw2 = float((w**2).sum())
164
+ num = group_g / (1.0 - single.sum_x2) - h - float((gam_j * w**2 * (1.0 - h_j)).sum())
165
+ return float(num / (1.0 - sw2))
shiftshare/analysis.py ADDED
@@ -0,0 +1,122 @@
1
+ """One-call summaries on labelled tables, used by the command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional, Sequence, Union
6
+
7
+ import numpy as np
8
+
9
+ from ._common import EmploymentTable, ShiftShareError
10
+ from .base import lq_method, minimum_requirements
11
+ from .decomposition import arcelus, classic, dynamic, esteban_marquillas
12
+ from .quotients import location_quotient
13
+ from .specialization import (
14
+ coefficient_of_localization,
15
+ coefficient_of_specialization,
16
+ herfindahl,
17
+ krugman_index,
18
+ localization_curve,
19
+ )
20
+
21
+ __all__ = ["profile", "decompose", "decompose_dynamic", "METHODS"]
22
+
23
+ METHODS = ("classic", "esteban-marquillas", "arcelus")
24
+
25
+
26
+ def _as_table(data: Any) -> EmploymentTable:
27
+ if isinstance(data, EmploymentTable):
28
+ return data
29
+ return EmploymentTable(np.asarray(data, dtype=float))
30
+
31
+
32
+ def profile(
33
+ table: Union[EmploymentTable, Any],
34
+ reference: Optional[Any] = None,
35
+ mr_rank: int = 1,
36
+ ) -> Dict[str, Any]:
37
+ """Structure of one cross-section: location quotients, specialisation per region
38
+ (Krugman index against the nation and the rest of the nation, coefficient of
39
+ specialisation, Herfindahl, LQ and minimum-requirements base multipliers) and
40
+ localisation per sector (Hoover coefficient and locational Gini)."""
41
+ t = _as_table(table)
42
+ e = t.values
43
+ lq = location_quotient(e, reference)
44
+ k_nat = krugman_index(e, reference, "nation")
45
+ k_rest = krugman_index(e, reference, "rest") if e.shape[0] > 1 else np.full(1, np.nan)
46
+ cs = coefficient_of_specialization(e, reference)
47
+ hhi = herfindahl(e)
48
+ lqb = lq_method(e, reference)
49
+ mrb = minimum_requirements(e, mr_rank) if e.shape[0] > 1 else None
50
+ regions = []
51
+ for i, r in enumerate(t.regions):
52
+ regions.append(
53
+ {
54
+ "region": r,
55
+ "employment": float(e[i].sum()),
56
+ "krugman_vs_nation": float(k_nat[i]),
57
+ "krugman_vs_rest": float(k_rest[i]),
58
+ "coefficient_of_specialization": float(cs[i]),
59
+ "herfindahl": float(hhi[i]),
60
+ "base_multiplier_lq": float(lqb.multiplier[i]),
61
+ "base_multiplier_mr": float(mrb.multiplier[i]) if mrb is not None else None,
62
+ }
63
+ )
64
+ cl = coefficient_of_localization(e)
65
+ sectors = []
66
+ for j, s in enumerate(t.sectors):
67
+ gini: Optional[float] = None
68
+ if e[:, j].sum() > 0:
69
+ gini = localization_curve(e, j).gini
70
+ sectors.append(
71
+ {
72
+ "sector": s,
73
+ "employment": float(e[:, j].sum()),
74
+ "coefficient_of_localization": float(cl[j]),
75
+ "locational_gini": gini,
76
+ }
77
+ )
78
+ return {
79
+ "regions": regions,
80
+ "sectors": sectors,
81
+ "location_quotients": t.label(lq, "lq"),
82
+ }
83
+
84
+
85
+ def decompose(
86
+ base: Union[EmploymentTable, Any],
87
+ end: Union[EmploymentTable, Any],
88
+ method: str = "classic",
89
+ national_base: Optional[Any] = None,
90
+ national_end: Optional[Any] = None,
91
+ ) -> Dict[str, Any]:
92
+ """Run a shift-share *method* (``classic``, ``esteban-marquillas`` or ``arcelus``) on
93
+ two labelled tables (the end table is aligned to the base labels) and return the JSON-
94
+ ready summary."""
95
+ b = _as_table(base)
96
+ e = b.aligned(end) if isinstance(end, EmploymentTable) else _as_table(end)
97
+ m = method.lower().replace("_", "-")
98
+ if m == "classic":
99
+ res: Any = classic(b.values, e.values, national_base, national_end)
100
+ elif m in ("esteban-marquillas", "esteban", "em"):
101
+ res = esteban_marquillas(b.values, e.values, national_base, national_end)
102
+ elif m == "arcelus":
103
+ res = arcelus(b.values, e.values, national_base, national_end)
104
+ else:
105
+ raise ShiftShareError(f"unknown method {method!r}; choose from {', '.join(METHODS)}")
106
+ out: Dict[str, Any] = res.to_dict(b.regions, b.sectors)
107
+ return out
108
+
109
+
110
+ def decompose_dynamic(
111
+ tables: Sequence[Union[EmploymentTable, Any]], national: Optional[Any] = None
112
+ ) -> Dict[str, Any]:
113
+ """Dynamic shift-share over labelled yearly tables (aligned to the first one)."""
114
+ if len(tables) < 2:
115
+ raise ShiftShareError("dynamic shift-share needs at least two years")
116
+ first = _as_table(tables[0])
117
+ vals = [first.values] + [
118
+ first.aligned(t).values if isinstance(t, EmploymentTable) else _as_table(t).values
119
+ for t in tables[1:]
120
+ ]
121
+ out: Dict[str, Any] = dynamic(np.stack(vals), national).to_dict(first.regions, first.sectors)
122
+ return out