-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.py
executable file
·215 lines (185 loc) · 6.66 KB
/
transform.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/bin/env python3
# python 3.5+
# SPDX-License-Identifier: MIT
import fileinput
import sys
from urllib.parse import urlencode
from collections import OrderedDict
aff_table = ("version", "lang", "program", "dataset", "product", "geoids", "codes")
aff_cf = ("version", "lang", "geo_type", "geo_name", "topic", "object")
cedsci = (
"target",
"q", # query
"t", # topics
"g", # geoids, underscore list
"y", # year
"d", # dataset
"n", # NAICS code
"p", # product/service code(s)
"table", # table id
"tid", # {dataset}{year}.{table id}
"comm", # commodity code
# table-specific parameters
"hidePreview",
"moe",
"tp",
# map-specific parameters
"layer",
"cid",
"palette",
"break",
"classification",
"mode",
"vintage",
)
def main(raw_url):
# remove protocol scheme
scheme, sep, old_url = raw_url.partition("//")
if not sep:
raise ValueError("Malformed URL")
# split into data fields
domain, tool, target, *data = old_url.split("/")
if tool not in {"bkmk"}:
# bkmk links have well-defined information
# faces links have little to no information
# servlet links may have useful information, but are not well-defined
raise ValueError("Not a stable deep link")
# handle different endpoints differently
if target == "table":
new_url = table(data)
# elif target == "navigation":
# new_url = navigation(data)
# elif target == "qs":
# new_url = qs(data)
elif target == "cf":
new_url = cf(data)
# elif target == "sm":
# new_url = sm(data)
# elif target == "select":
# new_url = select(data)
else:
raise NotImplementedError("No transformation rule for that data type")
return build_url(new_url)
def table(data):
"""Transforms AFF table URL data to CEDSCI table URL data"""
raw_data = OrderedDict(zip(aff_table, data))
survey, year, table_id = dataset_transform(
raw_data["program"], raw_data["dataset"], raw_data["product"]
)
new_data = OrderedDict(
target="table",
g=pipe_to_underscore(raw_data.get("geoids", "")),
y=year,
tid=survey + year + "." + table_id,
)
return new_data
def navigation(raw_data):
"""AFF search results to CEDSCI search results"""
raise NotImplementedError
def qs(raw_data):
"""AFF advanced search results to CEDSCI search results"""
raise NotImplementedError
def cf(data):
"""AFF Community Facts"""
# AFF linked to Community Facts by place name
# CEDSCI links to Community Profiles by GEOID, but we can get around
# that by using search instead
raw_data = OrderedDict(zip(aff_cf, data))
if raw_data["geo_type"] == "zip":
raise KeyError("CEDSCI does not support profiles for zipcodes")
new_data = OrderedDict(target="profile", q=raw_data["geo_name"])
return new_data
def sm(raw_data):
"""Transforms AFF reference map to CEDSCI map"""
raise NotImplementedError
def select(raw_data):
"""AFF overlay tabs"""
raise NotImplementedError
def dataset_transform(program, dataset, ds_table):
"""Transforms an AFF dataset identifier into the corresponding CEDSCI tid
Not all American FactFinder data has been moved to CEDSI.
Some is avaliable in other systems or the census website, while
other datasets will just plain become unavailable.
"""
survey, year = "", ""
# Programs not available at all
if program in {"ASM", "COG", "CFS", "PEP"}:
raise KeyError(program + " not yet available in CEDSCI")
elif program in {"AHS", "PP", "GEP", "SSF", "SGF", "STC", "BES", "SLF"}:
raise KeyError(program + " uses a different data access system")
elif program == "EEO":
raise KeyError("2010 EEO data not available on CEDSCI")
elif program == "ECN":
# TODO: Data likely exists, but tables don't line up
raise NotImplementedError("ECN tables don't line up between AFF and CEDSCI")
elif program == "BP":
# TODO No matter what the US Census Bureau says, CB1600CZ21 != CB1600ZBP
raise NotImplementedError(
"Table IDs for business patterns are not consistent between AFF and CEDSCI"
)
year = dataset
if int(year) < 2012 and survey == "CBP":
raise KeyError("Pre-2012 County Business Patterns not available in CEDSCI")
# Available or partially-available programs
elif program == "ACS":
new_table = ds_table
year = "20" + dataset[0:2]
if dataset.endswith("YR"):
survey = "ACSDT" + dataset[3:5]
else:
raise KeyError("Dataset does not exist on CEDSCI")
if int(year) < 2010:
raise KeyError("Pre-2010 ACS data not available on CEDSCI")
elif program == "DEC":
decennial = {
"113": "DECENNIALCD113",
"115": "DECENNIALCD115",
"SF1": "DECENNIALSF1",
}
year = "20" + dataset[0:2]
survey = decennial.get(dataset[-3:])
new_table = ds_table
if not survey:
raise KeyError("Decennial censusus data is not all available on CEDSCI")
elif program == "NES":
year = dataset
survey = "NONEMP"
new_table = "NS{0}00NONEMP".format(year[2:4])
if int(year) < 2012:
raise KeyError("Pre-2012 Nonemployer data not available on CEDSCI")
elif program == "SBO":
year = dataset
new_table = "SB" + year[-2:] + ds_table
if ds_table[-3] == "A":
survey = "SBOCS"
else:
raise KeyError(
"Survey of Business Owners tables other than "
"the company summary are not available on CEDSCI"
)
if not (survey and year and new_table):
raise KeyError(
"{0}/{1} could not be transformed to a CEDSCI survey".format(
program, dataset
)
)
else:
return survey, year, new_table
def pipe_to_underscore(pipelist):
"""Converts an AFF pipe-seperated list to a CEDSCI underscore-seperated list"""
return pipelist.replace("|", "_")
def build_url(data):
"""Builds a CEDSCI url from a Cedsci named tuple"""
assert set(data.keys()) <= set(cedsci)
base = "https://data.census.gov/cedsci/{0}?".format(data.pop("target"))
query = urlencode(OrderedDict((k, v) for k, v in sorted(data.items()) if v))
return base + query
if __name__ == "__main__":
if len(sys.argv) == 2 and sys.argv[1] != "-":
res = main(sys.argv[1].strip())
print(res)
else:
for line in fileinput.input():
if line:
res = main(line.strip())
print(res)