-
Notifications
You must be signed in to change notification settings - Fork 4
/
util.py
393 lines (314 loc) · 9.41 KB
/
util.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
import numpy as np
import pandas as pd
TEXTWIDTH = 118 # type: int
TAB = " " # type: str
SPACING = "\n\n" # type: str
# In Python 3.7 and newer, there is no limit. This limit applies to positional and keyword arguments.
MAX_PYTHON_3_6_ARG_COUNT = 255 # type: int
def make_module_docstring(description: str, file: Union[str, Path]) -> str:
"""Generates standard header with additional information from the description.
Parameters
----------
description
Custom header text for the generated file.
file
Path to python module that generates the target module.
Returns
-------
str
String representation of module doc string.
"""
here = Path(file).resolve()
out = f'"""{description}\n\n'
out += f"This code is automatically generated by {Path(*here.parts[-2:])}\n\n"
out += 'Any manual changes will be lost.\n"""\n'
return out
def make_import(module_to_import: str, imports: Tuple[str, ...] = ()) -> str:
"""Generates the necessary imports. Smart about importing modules or names.
Parameters
----------
module_to_import
Name of the module.
imports
Named items to import. If empty import the module name.
Returns
-------
str
Generated string for necessary imports.
"""
if not imports:
out = f"import {module_to_import}"
else:
out = text_wrap(f"from {module_to_import} import ", imports, implicit=True)
return out
def text_wrap(start_string, items, sep=", ", implicit=False):
if len(start_string + sep.join(items)) <= TEXTWIDTH:
out = start_string + sep.join(items) + "\n"
else:
out = start_string
if implicit:
out += "("
char_count = len(out)
padding = " " * char_count
out += items[0] + ", "
char_count += len(items[0]) + 2
for i in items[1:]:
if char_count + len(i) > TEXTWIDTH: # wrap
out = out[:-1] + "\n"
out += padding + i + ", "
char_count = len(padding + i + ", ")
else:
out += i + ", "
char_count += len(i) + 2
out = out[:-2]
if implicit:
out += ")"
out += "\n"
return out
def replace_numeric_prefix(name: str) -> str:
"""Variables cannot start with numeric characters. Replace with the word.
This only occurs 3 times using GBD 2019 data.
Parameters
----------
name
The name of the member variable.
Returns
-------
str
Input string transformed to non-numeric prefix.
"""
number_sub_map = {"2": "two", "4": "four", "12": "twelve"}
m = re.search("^[0-9]+", name)
if m:
name = f"{number_sub_map[m.group()]}_{name[m.span()[1]:]}"
return name
def clean_entity_list(raw_entity_series) -> List[str]:
replace_with_underscore_chars = [
"/",
"(",
")",
" – ",
" - ",
"-",
" ",
",",
"–",
"____",
"___",
"__",
"=",
]
replace_chars = {char: "_" for char in replace_with_underscore_chars}
replace_chars.update(
{
"'": "",
"’": "",
"[": "",
"]": "",
"^": "",
"é": "e",
"<": "less_than_",
">": "greater_than_",
"+": "_and_up",
"I$": "income",
"%": "_percent",
"90th": "ninetieth",
"*": "x",
":": "",
";": "",
"#": "",
"&": "and",
"10_year": "ten_year",
"year.": "year",
"PM_2.5": "pm_2_5",
"PM2.5": "pm_2_5",
}
)
cleaned_up_entities = []
for entity in list(raw_entity_series):
entity = str(entity)
# Clean up the string
for char, rep_char in replace_chars.items():
entity = entity.replace(char, rep_char)
entity = replace_numeric_prefix(entity)
entity = entity.lower().rstrip().rstrip("_")
cleaned_up_entities.append(entity)
return cleaned_up_entities
def to_id(number: float, id_type: str) -> str:
"""Wrap the id value with the id type. Be mindful of NaN values.
Parameters
----------
number
The id value.
id_type
The id type.
Returns
-------
str
String with the id type wrapping the value in parentheses.
"""
if np.isnan(number):
return "UNKNOWN"
else:
return id_type + f"({int(number)})"
def make_class_sig(name, superclass=None, docstring=None) -> str:
"""Generate class signature from a name and additional information.
Parameters
----------
name
Name of the generated class.
superclass
Parent class.
docstring
Documentation for the generated class.
Returns
-------
str
String representation of named class.
"""
out = f"class {name}"
if superclass[0]:
out += f"({superclass[0]})"
out += ":\n"
if docstring:
out += TAB + f'"""{docstring}"""\n'
return out
def make_slots(field_list: List[str]) -> str:
"""Generate explicit object attributes using slots (instead of dict).
Parameters
----------
field_list
Names for the slot attributes.
Returns
-------
str
String representation of slot attributes.
"""
declaration = TAB + "__slots__ = ("
offset = len(declaration)
out = declaration
char_count = offset
for field in field_list:
field = f"'{field}', "
field_width = len(field)
if char_count == offset:
out += field
char_count += field_width
elif char_count + field_width > TEXTWIDTH:
out = out[:-1] + "\n" + " " * offset + field
char_count = offset + field_width
else:
out += field
char_count += field_width
out += ")\n\n"
return out
def make_init(field_dtype_tuples: Tuple[Tuple[str, str], ...]) -> str:
"""Generate the __init__ function as part of class generation.
Parameters
----------
field_dtype_tuples
Collection of name / value pairs that are used to create the
the __init__ function with the specified parameters. Parameters
are type hinted.
Returns
-------
str
String representation of the __init__ function.
"""
declaration = TAB + "def __init__("
offset = len(declaration)
out = declaration + "self,"
if len(field_dtype_tuples) > MAX_PYTHON_3_6_ARG_COUNT:
out += " " + "**kwargs):\n"
else:
out += "\n"
for field_name, data_type in field_dtype_tuples:
out += " " * offset + field_name + ": " + data_type + ",\n"
out = out[:-1] + " ):\n"
return out
def make_super_call(superclass: Tuple[str, Tuple[Tuple[str, str], ...]]) -> str:
"""Generate the call to initialize the parent class.
Parameters
----------
superclass
Nested tuples composed of name and attributes for the superclass.
Returns
-------
str
String representation of the call to the superclass.
"""
field_names = [attr[0] for attr in superclass[1]]
declaration = 2 * TAB + "super().__init__("
if not field_names:
return declaration + ")\n"
offset = len(declaration)
out = declaration
for field in field_names:
out += f"{field}={field},\n"
out += " " * offset
out = out[: -offset - 2] + ")\n"
return out
def make_attribute_assignment(field_names: List[str]) -> str:
"""Generate the class attributes and initialize them.
Parameters
----------
field_names
List of class attribute names.
Returns
-------
str
String representation of the initialized attributes.
"""
offset = 8
out = ""
if len(field_names) > MAX_PYTHON_3_6_ARG_COUNT:
for field in field_names:
out += " " * offset + f"self.{field} = kwargs.get('{field}')\n"
else:
for field in field_names:
out += " " * offset + f"self.{field} = {field}\n"
return out
def make_record(
name: str,
attrs: Tuple[Tuple[str, str], ...] = None,
superclass: Tuple[str, Tuple[Tuple[str, str], ...]] = None,
docstring: str = None,
):
"""Generate class definitions from a name and additional information.
Parameters
----------
name
Name of the generated class.
attrs
Class attributes.
superclass
Parent class.
docstring
Documentation for the generated class.
Returns
-------
str
String representation of named class.
"""
out = ""
out += make_class_sig(name, superclass, docstring)
out += make_slots([attr[0] for attr in attrs])
out += make_init(attrs)
if superclass:
out += make_super_call(superclass)
out += make_attribute_assignment([attr[0] for attr in attrs])
return out
def get_default_output_directory():
here = os.path.realpath(__file__)
return os.path.realpath(os.path.dirname(here) + "/../ceam_inputs/gbd_mapping/")
def format_string_none(value):
if value is None:
return None
else:
return f"'{value}'"
def make_empty_survey(flags, index):
return pd.DataFrame(dict(zip(flags, [None] * len(flags))), index=index)