uspatial 0.2.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.
- uspatial/__init__.py +84 -0
- uspatial/__main__.py +7 -0
- uspatial/cli.py +269 -0
- uspatial/data.py +144 -0
- uspatial/diagnostics.py +608 -0
- uspatial/models.py +744 -0
- uspatial/reporting.py +152 -0
- uspatial/visualization.py +254 -0
- uspatial/weights.py +168 -0
- uspatial-0.2.0.dist-info/METADATA +224 -0
- uspatial-0.2.0.dist-info/RECORD +15 -0
- uspatial-0.2.0.dist-info/WHEEL +5 -0
- uspatial-0.2.0.dist-info/entry_points.txt +2 -0
- uspatial-0.2.0.dist-info/licenses/LICENSE +21 -0
- uspatial-0.2.0.dist-info/top_level.txt +1 -0
uspatial/__init__.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Urban Spatial Econometric Analysis — 공간계량 분석 라이브러리
|
|
3
|
+
|
|
4
|
+
PySAL(spreg·esda·libpysal)과 mgwr를 감싸 도시·부동산 연구의 표준 워크플로를
|
|
5
|
+
제공한다: 가중행렬 → 공간 진단(Moran's I / LISA / LM) → 모형 추정
|
|
6
|
+
(OLS·SLM·SEM·SDM·GWR) → 직접·간접효과 분해 → 출판용 표.
|
|
7
|
+
|
|
8
|
+
사용 예:
|
|
9
|
+
>>> from uspatial import SpatialModel, build_weights, select_model
|
|
10
|
+
>>> w = build_weights(gdf, method="queen")
|
|
11
|
+
>>> selection = select_model(gdf, "log_price", ["inc", "dist_cbd"], w)
|
|
12
|
+
>>> print(selection.recommendation) # 'SLM' | 'SEM' | 'OLS' | 'SDM'
|
|
13
|
+
>>> result = selection.fit(gdf, "log_price", ["inc", "dist_cbd"], w)
|
|
14
|
+
>>> print(result.summary())
|
|
15
|
+
|
|
16
|
+
명령줄:
|
|
17
|
+
python -m uspatial examples
|
|
18
|
+
python -m uspatial estimate --data tracts.csv --y log_price --x inc,dist_cbd \\
|
|
19
|
+
--coords lon,lat --knn 6 --method SEM
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from uspatial.data import describe_dataset, load_example
|
|
23
|
+
from uspatial.diagnostics import (
|
|
24
|
+
LisaResult,
|
|
25
|
+
LMTestResult,
|
|
26
|
+
MoranResult,
|
|
27
|
+
gearys_c,
|
|
28
|
+
lm_diagnostics,
|
|
29
|
+
local_moran,
|
|
30
|
+
morans_i,
|
|
31
|
+
residual_moran,
|
|
32
|
+
spatial_chow_test,
|
|
33
|
+
variance_inflation_factor,
|
|
34
|
+
)
|
|
35
|
+
from uspatial.models import (
|
|
36
|
+
SelectionResult,
|
|
37
|
+
SpatialModel,
|
|
38
|
+
SpatialResults,
|
|
39
|
+
compare_models,
|
|
40
|
+
impacts_decomposition,
|
|
41
|
+
select_model,
|
|
42
|
+
)
|
|
43
|
+
from uspatial.reporting import (
|
|
44
|
+
coefficient_table,
|
|
45
|
+
latex_table,
|
|
46
|
+
markdown_table,
|
|
47
|
+
model_comparison_table,
|
|
48
|
+
)
|
|
49
|
+
from uspatial.weights import build_weights, weights_summary
|
|
50
|
+
|
|
51
|
+
__version__ = "0.2.0"
|
|
52
|
+
__author__ = "Dongsoo Jung"
|
|
53
|
+
__email__ = "jds068888@gmail.com"
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
# models
|
|
57
|
+
"SpatialModel",
|
|
58
|
+
"SpatialResults",
|
|
59
|
+
"SelectionResult",
|
|
60
|
+
"select_model",
|
|
61
|
+
"compare_models",
|
|
62
|
+
"impacts_decomposition",
|
|
63
|
+
# diagnostics
|
|
64
|
+
"morans_i",
|
|
65
|
+
"gearys_c",
|
|
66
|
+
"local_moran",
|
|
67
|
+
"lm_diagnostics",
|
|
68
|
+
"variance_inflation_factor",
|
|
69
|
+
"spatial_chow_test",
|
|
70
|
+
"residual_moran",
|
|
71
|
+
"MoranResult",
|
|
72
|
+
"LisaResult",
|
|
73
|
+
"LMTestResult",
|
|
74
|
+
# weights & data
|
|
75
|
+
"build_weights",
|
|
76
|
+
"weights_summary",
|
|
77
|
+
"load_example",
|
|
78
|
+
"describe_dataset",
|
|
79
|
+
# reporting
|
|
80
|
+
"coefficient_table",
|
|
81
|
+
"markdown_table",
|
|
82
|
+
"latex_table",
|
|
83
|
+
"model_comparison_table",
|
|
84
|
+
]
|
uspatial/__main__.py
ADDED
uspatial/cli.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""
|
|
2
|
+
``uspatial`` 명령줄 도구
|
|
3
|
+
|
|
4
|
+
노트북을 열지 않고도 CSV 하나로 진단 → 추정 → 표 출력까지 수행한다.
|
|
5
|
+
|
|
6
|
+
python -m uspatial examples
|
|
7
|
+
python -m uspatial diagnose --data tracts.csv --y log_price --x inc,dist_cbd \\
|
|
8
|
+
--coords lon,lat --knn 6
|
|
9
|
+
python -m uspatial estimate --data tracts.csv --y log_price --x inc,dist_cbd \\
|
|
10
|
+
--coords lon,lat --knn 6 --method SEM --format markdown
|
|
11
|
+
|
|
12
|
+
좌표는 ``--coords``로 지정한 두 열(경도/위도 또는 투영 X/Y)에서 읽는다. 거리 기반
|
|
13
|
+
가중행렬은 좌표 단위를 그대로 쓰므로, 경위도(EPSG:4326)를 쓰면 이웃 수(k)만
|
|
14
|
+
의미가 있고 거리 밴드는 도(degree) 단위가 된다 — 이때는 ``--knn``을 권한다.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
from collections.abc import Sequence
|
|
22
|
+
|
|
23
|
+
import pandas as pd
|
|
24
|
+
|
|
25
|
+
from uspatial.diagnostics import local_moran, morans_i
|
|
26
|
+
from uspatial.models import METHODS, SpatialModel, impacts_decomposition, select_model
|
|
27
|
+
from uspatial.reporting import (
|
|
28
|
+
coefficient_table,
|
|
29
|
+
latex_table,
|
|
30
|
+
markdown_table,
|
|
31
|
+
model_comparison_table,
|
|
32
|
+
)
|
|
33
|
+
from uspatial.weights import build_weights, weights_summary
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _load_points(path: str, coords: Sequence[str]):
|
|
37
|
+
"""CSV → (DataFrame, GeoDataFrame|None)."""
|
|
38
|
+
frame = pd.read_csv(path)
|
|
39
|
+
if not coords:
|
|
40
|
+
return frame, None
|
|
41
|
+
if len(coords) != 2:
|
|
42
|
+
raise SystemExit("--coords takes exactly two column names, e.g. lon,lat")
|
|
43
|
+
import geopandas as gpd
|
|
44
|
+
from shapely.geometry import Point
|
|
45
|
+
|
|
46
|
+
missing = [c for c in coords if c not in frame.columns]
|
|
47
|
+
if missing:
|
|
48
|
+
raise SystemExit(f"coordinate columns not found: {missing}")
|
|
49
|
+
geometry = [Point(xy) for xy in zip(frame[coords[0]], frame[coords[1]], strict=True)]
|
|
50
|
+
return frame, gpd.GeoDataFrame(frame, geometry=geometry)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _weights(frame: pd.DataFrame, points, knn: int, method: str):
|
|
54
|
+
source = points if points is not None else frame
|
|
55
|
+
if points is None and method in ("queen", "rook", "knn", "distance", "kernel"):
|
|
56
|
+
raise SystemExit(
|
|
57
|
+
"spatial weights need coordinates: pass --coords lon,lat (points) "
|
|
58
|
+
"or a GeoDataFrame input"
|
|
59
|
+
)
|
|
60
|
+
n = len(source)
|
|
61
|
+
if method == "knn" and knn >= n:
|
|
62
|
+
raise SystemExit(
|
|
63
|
+
f"--knn {knn} is not possible with {n} observations; "
|
|
64
|
+
f"choose k <= {max(n - 1, 1)}"
|
|
65
|
+
)
|
|
66
|
+
return build_weights(source, method=method, k=knn)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _print_weights(weights) -> None:
|
|
70
|
+
summary = weights_summary(weights)
|
|
71
|
+
print(
|
|
72
|
+
"Weights: n={n} mean_neighbors={mean_neighbors:.2f} "
|
|
73
|
+
"islands={islands:.1%} symmetric={symmetric}".format(
|
|
74
|
+
islands=summary["pct_islands"], **summary
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def cmd_examples(_: argparse.Namespace) -> int:
|
|
80
|
+
from uspatial.data import DATASET_INFO
|
|
81
|
+
|
|
82
|
+
print("Built-in PySAL example datasets (uspatial.data.load_example):")
|
|
83
|
+
for name, info in DATASET_INFO.items():
|
|
84
|
+
print(f" {name:<10} {info['description']}")
|
|
85
|
+
print(f" {'':<10} key variables: {', '.join(info['key_vars'])}")
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
90
|
+
frame, points = _load_points(args.data, args.coords or [])
|
|
91
|
+
weights = _weights(frame, points, args.knn, args.weights)
|
|
92
|
+
_print_weights(weights)
|
|
93
|
+
|
|
94
|
+
y = frame[args.y].to_numpy(dtype=float)
|
|
95
|
+
moran = morans_i(y, weights, permutations=args.permutations, seed=args.seed)
|
|
96
|
+
print(f"Moran's I ({args.y}): {moran.interpret()}")
|
|
97
|
+
|
|
98
|
+
if args.lisa:
|
|
99
|
+
lisa = local_moran(y, weights, permutations=args.permutations, seed=args.seed)
|
|
100
|
+
print(lisa.summary())
|
|
101
|
+
if args.output:
|
|
102
|
+
frame.assign(lisa_cluster=lisa.cluster_labels, lisa_p=lisa.p_values).to_csv(
|
|
103
|
+
args.output, index=False
|
|
104
|
+
)
|
|
105
|
+
print(f"LISA columns written to {args.output}")
|
|
106
|
+
|
|
107
|
+
selection = select_model(frame, args.y, args.x, weights, alpha=args.alpha)
|
|
108
|
+
print()
|
|
109
|
+
print("LM diagnostics:")
|
|
110
|
+
print(selection.diagnostics.to_frame().to_string(float_format=lambda v: f"{v:.4f}"))
|
|
111
|
+
print(f" {selection.diagnostics.rule}")
|
|
112
|
+
print(f" Recommended model: {selection.recommendation}")
|
|
113
|
+
return 0
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cmd_estimate(args: argparse.Namespace) -> int:
|
|
117
|
+
frame, points = _load_points(args.data, args.coords or [])
|
|
118
|
+
weights = _weights(frame, points, args.knn, args.weights)
|
|
119
|
+
_print_weights(weights)
|
|
120
|
+
|
|
121
|
+
model = SpatialModel(
|
|
122
|
+
df=frame, y=args.y, X=args.x, w=weights, method=args.method
|
|
123
|
+
)
|
|
124
|
+
result = model.fit()
|
|
125
|
+
print()
|
|
126
|
+
print(result.summary())
|
|
127
|
+
|
|
128
|
+
if args.method in ("SLM", "SDM") and args.impacts is not None:
|
|
129
|
+
impacts = impacts_decomposition(result, draws=args.impacts, seed=args.seed)
|
|
130
|
+
print()
|
|
131
|
+
print("Direct / indirect / total effects:")
|
|
132
|
+
print(impacts.to_string(float_format=lambda v: f"{v:.4f}"))
|
|
133
|
+
|
|
134
|
+
if args.format != "text":
|
|
135
|
+
table = coefficient_table(result)
|
|
136
|
+
if args.format == "markdown":
|
|
137
|
+
print()
|
|
138
|
+
print(markdown_table(table, caption=f"{args.method}: {args.y}"))
|
|
139
|
+
else:
|
|
140
|
+
print()
|
|
141
|
+
print(
|
|
142
|
+
latex_table(
|
|
143
|
+
table,
|
|
144
|
+
caption=f"{args.method}: {args.y}",
|
|
145
|
+
label=f"tab:{args.method.lower()}",
|
|
146
|
+
notes=[
|
|
147
|
+
"Note: *** p<0.001, ** p<0.01, * p<0.05, . p<0.1.",
|
|
148
|
+
],
|
|
149
|
+
)
|
|
150
|
+
)
|
|
151
|
+
if args.output:
|
|
152
|
+
frame.assign(fitted=result.fitted_values, resid=result.residuals).to_csv(
|
|
153
|
+
args.output, index=False
|
|
154
|
+
)
|
|
155
|
+
print(f"Fitted values and residuals written to {args.output}")
|
|
156
|
+
return 0
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def cmd_compare(args: argparse.Namespace) -> int:
|
|
160
|
+
frame, points = _load_points(args.data, args.coords or [])
|
|
161
|
+
weights = _weights(frame, points, args.knn, args.weights)
|
|
162
|
+
_print_weights(weights)
|
|
163
|
+
|
|
164
|
+
results = [
|
|
165
|
+
SpatialModel(df=frame, y=args.y, X=args.x, w=weights, method=method).fit()
|
|
166
|
+
for method in args.methods
|
|
167
|
+
]
|
|
168
|
+
table = model_comparison_table(results)
|
|
169
|
+
print()
|
|
170
|
+
if args.format == "latex":
|
|
171
|
+
print(latex_table(table, caption=f"Model comparison: {args.y}", index_name="Model"))
|
|
172
|
+
elif args.format == "markdown":
|
|
173
|
+
print(markdown_table(table, caption=f"Model comparison: {args.y}", index_name="Model"))
|
|
174
|
+
else:
|
|
175
|
+
print(table.to_string())
|
|
176
|
+
if args.json:
|
|
177
|
+
print(
|
|
178
|
+
json.dumps(
|
|
179
|
+
{
|
|
180
|
+
result.method: {
|
|
181
|
+
"aic": result.aic,
|
|
182
|
+
"bic": result.bic,
|
|
183
|
+
"r2": result.r2,
|
|
184
|
+
"pseudo_r2": result.pseudo_r2,
|
|
185
|
+
"rho": result.rho,
|
|
186
|
+
"lambda": result.lambda_,
|
|
187
|
+
}
|
|
188
|
+
for result in results
|
|
189
|
+
},
|
|
190
|
+
ensure_ascii=False,
|
|
191
|
+
indent=2,
|
|
192
|
+
default=float,
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
return 0
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
199
|
+
parser = argparse.ArgumentParser(prog="uspatial", description=__doc__.splitlines()[0])
|
|
200
|
+
parser.add_argument("--version", action="version", version="uspatial 0.2.0")
|
|
201
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
202
|
+
|
|
203
|
+
def add_data_options(target: argparse.ArgumentParser) -> None:
|
|
204
|
+
target.add_argument("--data", required=True, help="CSV with one row per spatial unit")
|
|
205
|
+
target.add_argument("--y", required=True, help="dependent variable column")
|
|
206
|
+
target.add_argument("--x", required=True, help="comma-separated regressor columns")
|
|
207
|
+
target.add_argument("--coords", default=None, help="comma-separated lon,lat columns")
|
|
208
|
+
target.add_argument(
|
|
209
|
+
"--weights",
|
|
210
|
+
default="knn",
|
|
211
|
+
choices=["queen", "rook", "knn", "distance", "kernel"],
|
|
212
|
+
help="spatial weights method (default: knn)",
|
|
213
|
+
)
|
|
214
|
+
target.add_argument("--knn", type=int, default=6, help="neighbours for knn weights")
|
|
215
|
+
target.add_argument("--seed", type=int, default=0)
|
|
216
|
+
target.add_argument("--output", default=None, help="optional CSV to write results to")
|
|
217
|
+
|
|
218
|
+
examples = sub.add_parser("examples", help="list built-in example datasets")
|
|
219
|
+
examples.set_defaults(func=cmd_examples)
|
|
220
|
+
|
|
221
|
+
diagnose = sub.add_parser("diagnose", help="Moran's I, LISA, LM diagnostics")
|
|
222
|
+
add_data_options(diagnose)
|
|
223
|
+
diagnose.add_argument("--permutations", type=int, default=999)
|
|
224
|
+
diagnose.add_argument("--alpha", type=float, default=0.05)
|
|
225
|
+
diagnose.add_argument("--lisa", action="store_true", help="also compute local Moran")
|
|
226
|
+
diagnose.set_defaults(func=cmd_diagnose)
|
|
227
|
+
|
|
228
|
+
estimate = sub.add_parser("estimate", help="estimate one spatial model")
|
|
229
|
+
add_data_options(estimate)
|
|
230
|
+
estimate.add_argument("--method", default="OLS", choices=list(METHODS))
|
|
231
|
+
estimate.add_argument(
|
|
232
|
+
"--impacts",
|
|
233
|
+
type=int,
|
|
234
|
+
default=None,
|
|
235
|
+
help="draw N simulations for impact standard errors (SLM/SDM)",
|
|
236
|
+
)
|
|
237
|
+
estimate.add_argument("--format", default="text", choices=["text", "markdown", "latex"])
|
|
238
|
+
estimate.set_defaults(func=cmd_estimate)
|
|
239
|
+
|
|
240
|
+
compare = sub.add_parser("compare", help="estimate several models and compare fit")
|
|
241
|
+
add_data_options(compare)
|
|
242
|
+
compare.add_argument(
|
|
243
|
+
"--methods",
|
|
244
|
+
default="OLS,SLM,SEM",
|
|
245
|
+
help="comma-separated models to estimate (default: OLS,SLM,SEM)",
|
|
246
|
+
)
|
|
247
|
+
compare.add_argument("--format", default="text", choices=["text", "markdown", "latex"])
|
|
248
|
+
compare.add_argument("--json", action="store_true", help="also print fit statistics as JSON")
|
|
249
|
+
compare.set_defaults(func=cmd_compare)
|
|
250
|
+
return parser
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
254
|
+
parser = build_parser()
|
|
255
|
+
args = parser.parse_args(argv)
|
|
256
|
+
if getattr(args, "x", None):
|
|
257
|
+
args.x = [name.strip() for name in args.x.split(",") if name.strip()]
|
|
258
|
+
if getattr(args, "coords", None):
|
|
259
|
+
args.coords = [name.strip() for name in args.coords.split(",") if name.strip()]
|
|
260
|
+
if getattr(args, "methods", None):
|
|
261
|
+
args.methods = [name.strip() for name in args.methods.split(",") if name.strip()]
|
|
262
|
+
unknown = [m for m in args.methods if m not in METHODS]
|
|
263
|
+
if unknown:
|
|
264
|
+
raise SystemExit(f"unknown method(s): {unknown}; choose from {METHODS}")
|
|
265
|
+
try:
|
|
266
|
+
return args.func(args)
|
|
267
|
+
except (ValueError, ImportError) as exc:
|
|
268
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
269
|
+
return 2
|
uspatial/data.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""
|
|
2
|
+
예제 데이터 로더
|
|
3
|
+
|
|
4
|
+
PySAL 내장 예제 데이터셋을 즉시 로드하여 튜토리얼에 활용.
|
|
5
|
+
외부 API 없이 공간계량 모형을 바로 실험할 수 있다.
|
|
6
|
+
|
|
7
|
+
제공 데이터셋:
|
|
8
|
+
- Columbus (Ohio, USA) : 49개 census tract × 범죄·주거 변수
|
|
9
|
+
- Baltimore : 211개 주택 × 가격·입지
|
|
10
|
+
- NAT : 3,085개 US county × 살인율 패널 (1960-90)
|
|
11
|
+
- NCOVR : NAT의 서브셋, 간단한 튜토리얼용
|
|
12
|
+
- Boston : 506 × 13 속성 (Harrison-Rubinfeld 1978)
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Literal
|
|
19
|
+
|
|
20
|
+
import geopandas as gpd
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
DatasetName = Literal["columbus", "baltim", "nat", "ncovr", "boston"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_example(
|
|
29
|
+
name: DatasetName = "columbus",
|
|
30
|
+
return_gdf: bool = True,
|
|
31
|
+
) -> gpd.GeoDataFrame | pd.DataFrame:
|
|
32
|
+
"""
|
|
33
|
+
PySAL 내장 예제 데이터셋 로드.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
name: 데이터셋 이름
|
|
37
|
+
return_gdf: True면 GeoDataFrame, False면 속성만 담은 DataFrame
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
선택된 데이터셋
|
|
41
|
+
|
|
42
|
+
Example:
|
|
43
|
+
>>> gdf = load_example("columbus")
|
|
44
|
+
>>> gdf.shape
|
|
45
|
+
(49, 21)
|
|
46
|
+
>>> gdf.columns.tolist()[:5]
|
|
47
|
+
['AREA', 'PERIMETER', 'COLUMBUS_', 'COLUMBUS_I', 'POLYID']
|
|
48
|
+
"""
|
|
49
|
+
from libpysal.examples import load_example as _pysal_load
|
|
50
|
+
|
|
51
|
+
# libpysal 예제명 + shapefile 매핑
|
|
52
|
+
mapping = {
|
|
53
|
+
"columbus": ("Columbus", "columbus.shp"),
|
|
54
|
+
"baltim": ("Baltimore", "baltim.shp"),
|
|
55
|
+
"nat": ("NAT", "NAT.shp"),
|
|
56
|
+
"ncovr": ("NAT", "NAT.shp"),
|
|
57
|
+
"boston": ("Bostonhsg", "bostonhsg.shp"),
|
|
58
|
+
}
|
|
59
|
+
if name not in mapping:
|
|
60
|
+
raise ValueError(
|
|
61
|
+
f"지원하지 않는 데이터셋: {name!r}. "
|
|
62
|
+
f"{list(mapping)} 중 선택."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
proper, shp = mapping[name]
|
|
66
|
+
try:
|
|
67
|
+
# columbus·baltim 은 libpysal 에 동봉되어 있어 네트워크 없이 읽는다.
|
|
68
|
+
from libpysal.examples import get_path
|
|
69
|
+
path = get_path(shp)
|
|
70
|
+
except (KeyError, FileNotFoundError, AttributeError):
|
|
71
|
+
path = None
|
|
72
|
+
if path is None or not Path(path).exists():
|
|
73
|
+
example = _pysal_load(proper) # 원격 예제 (최초 1회 다운로드)
|
|
74
|
+
path = example.get_path(shp)
|
|
75
|
+
gdf = gpd.read_file(path)
|
|
76
|
+
|
|
77
|
+
if return_gdf:
|
|
78
|
+
return gdf
|
|
79
|
+
return pd.DataFrame(gdf.drop(columns="geometry"))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def describe_dataset(name: DatasetName) -> dict:
|
|
83
|
+
"""
|
|
84
|
+
데이터셋 메타정보 반환.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
{
|
|
88
|
+
'name': str,
|
|
89
|
+
'n_obs': int,
|
|
90
|
+
'n_vars': int,
|
|
91
|
+
'geometry_type': str,
|
|
92
|
+
'crs': str,
|
|
93
|
+
'key_variables': list[str],
|
|
94
|
+
'citation': str,
|
|
95
|
+
}
|
|
96
|
+
"""
|
|
97
|
+
meta = {
|
|
98
|
+
"columbus": dict(n_obs=49, n_vars=21, geometry_type="Polygon"),
|
|
99
|
+
"baltim": dict(n_obs=211, n_vars=17, geometry_type="Point"),
|
|
100
|
+
"nat": dict(n_obs=3085, n_vars=69, geometry_type="Polygon"),
|
|
101
|
+
"ncovr": dict(n_obs=3085, n_vars=69, geometry_type="Polygon"),
|
|
102
|
+
"boston": dict(n_obs=506, n_vars=23, geometry_type="Polygon"),
|
|
103
|
+
}
|
|
104
|
+
if name not in meta:
|
|
105
|
+
raise ValueError(f"지원하지 않는 데이터셋: {name!r}")
|
|
106
|
+
|
|
107
|
+
info = DATASET_INFO.get(name, {})
|
|
108
|
+
m = meta[name]
|
|
109
|
+
return {
|
|
110
|
+
"name": name,
|
|
111
|
+
"n_obs": m["n_obs"],
|
|
112
|
+
"n_vars": m["n_vars"],
|
|
113
|
+
"geometry_type": m["geometry_type"],
|
|
114
|
+
"crs": "EPSG:4326",
|
|
115
|
+
"key_variables": info.get("key_vars", []),
|
|
116
|
+
"citation": info.get("citation", ""),
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ----------------------------------------------------------------------
|
|
121
|
+
# 데이터셋 설명 (참조용)
|
|
122
|
+
# ----------------------------------------------------------------------
|
|
123
|
+
DATASET_INFO = {
|
|
124
|
+
"columbus": {
|
|
125
|
+
"description": "49 neighborhoods in Columbus, OH (1980)",
|
|
126
|
+
"key_vars": ["CRIME", "INC", "HOVAL"],
|
|
127
|
+
"citation": "Anselin (1988), Spatial Econometrics, ch.12",
|
|
128
|
+
},
|
|
129
|
+
"baltim": {
|
|
130
|
+
"description": "211 houses sold in Baltimore (1978)",
|
|
131
|
+
"key_vars": ["PRICE", "SQFT", "AGE", "ROOMS"],
|
|
132
|
+
"citation": "Dubin (1992), Regional Science and Urban Economics",
|
|
133
|
+
},
|
|
134
|
+
"nat": {
|
|
135
|
+
"description": "3,085 US counties, homicide 1960-1990",
|
|
136
|
+
"key_vars": ["HR60", "HR70", "HR80", "HR90", "PO60-PO90"],
|
|
137
|
+
"citation": "Messner & Anselin (1999)",
|
|
138
|
+
},
|
|
139
|
+
"boston": {
|
|
140
|
+
"description": "506 census tracts in Boston (1970)",
|
|
141
|
+
"key_vars": ["MEDV", "NOX", "RM", "DIS", "TAX"],
|
|
142
|
+
"citation": "Harrison & Rubinfeld (1978), JEEM",
|
|
143
|
+
},
|
|
144
|
+
}
|