AtlasIO 0.2.4__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.
- atlasio/__init__.py +266 -0
- atlasio/__main__.py +30 -0
- atlasio/_convert.py +192 -0
- atlasio/_write.py +309 -0
- atlasio-0.2.4.dist-info/METADATA +102 -0
- atlasio-0.2.4.dist-info/RECORD +10 -0
- atlasio-0.2.4.dist-info/WHEEL +5 -0
- atlasio-0.2.4.dist-info/entry_points.txt +2 -0
- atlasio-0.2.4.dist-info/licenses/LICENSE +21 -0
- atlasio-0.2.4.dist-info/top_level.txt +1 -0
atlasio/__init__.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""atlasio: read and write Atlas files (redistricting map ensembles) in Python, and convert between format versions.
|
|
2
|
+
|
|
3
|
+
An Atlas file holds one header and then one district map per line; the format is described in
|
|
4
|
+
https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md. This package reads and writes format versions 1
|
|
5
|
+
and 2, plain or compressed (.gz, .bz2), and converts files between the two versions (``convert``, or
|
|
6
|
+
``python -m atlasio convert SRC DST --to 2`` on the command line).
|
|
7
|
+
|
|
8
|
+
import atlasio
|
|
9
|
+
|
|
10
|
+
with atlasio.open_atlas("atlas.jsonl.gz") as atlas:
|
|
11
|
+
print(atlas.description, atlas.format_version, atlas.params)
|
|
12
|
+
for m in atlas:
|
|
13
|
+
m.name, m.weight, m.data
|
|
14
|
+
m.districting[("MECKLENBURG", "052")] # district keys are tuples, as in AtlasIO.jl
|
|
15
|
+
|
|
16
|
+
with atlasio.new_atlas("out.jsonl.gz", description="my ensemble", params={"districts": 14}) as out:
|
|
17
|
+
out.add_map("map1", {("WAKE",): 3, ("MECKLENBURG", "052"): 13}, weight=1, data={"score": 0.5})
|
|
18
|
+
|
|
19
|
+
Only the standard library is needed. If the optional ``orjson`` package is installed it is used to parse
|
|
20
|
+
lines faster (any line orjson refuses, such as one with NaN, falls back to the standard json module).
|
|
21
|
+
"""
|
|
22
|
+
import bz2
|
|
23
|
+
import gzip
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
|
|
28
|
+
__version__ = "0.2.4"
|
|
29
|
+
|
|
30
|
+
__all__ = ["open_atlas", "Atlas", "Map", "AtlasFormatError", "parse_map", "parse_district_key",
|
|
31
|
+
"district_key_string", "new_atlas", "AtlasWriter", "map_json", "convert", "FORMAT_VERSIONS",
|
|
32
|
+
"__version__"]
|
|
33
|
+
|
|
34
|
+
#: The Atlas format versions this package reads and writes.
|
|
35
|
+
FORMAT_VERSIONS = ("1", "2")
|
|
36
|
+
|
|
37
|
+
_REQUIRED_HEADER = ("description", "date", "atlasParamType", "mapParamType")
|
|
38
|
+
|
|
39
|
+
try: # optional speed-up
|
|
40
|
+
import orjson as _orjson
|
|
41
|
+
|
|
42
|
+
def _loads(s):
|
|
43
|
+
try:
|
|
44
|
+
return _orjson.loads(s)
|
|
45
|
+
except _orjson.JSONDecodeError:
|
|
46
|
+
return json.loads(s) # e.g. NaN or integers beyond 64 bits, which the json module accepts
|
|
47
|
+
except ImportError: # pragma: no cover - depends on the environment
|
|
48
|
+
_loads = json.loads
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AtlasFormatError(ValueError):
|
|
52
|
+
"""The file or line is not a valid Atlas (or uses a format version this package does not read)."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Map:
|
|
56
|
+
"""One map: ``name``, ``weight``, ``data`` and ``districting``.
|
|
57
|
+
|
|
58
|
+
``districting`` maps each region's key, a tuple of names from the coarsest level down, such as
|
|
59
|
+
``("WAKE",)`` or ``("MECKLENBURG", "052")``, to its district number. It is the same for a map read from a
|
|
60
|
+
v1 file and from a v2 file.
|
|
61
|
+
"""
|
|
62
|
+
__slots__ = ("name", "weight", "data", "districting")
|
|
63
|
+
|
|
64
|
+
def __init__(self, name, weight, data, districting):
|
|
65
|
+
self.name = name
|
|
66
|
+
self.weight = weight
|
|
67
|
+
self.data = data
|
|
68
|
+
self.districting = districting
|
|
69
|
+
|
|
70
|
+
def raw_districting(self):
|
|
71
|
+
"""The districting with v1-style string keys, e.g. ``'["MECKLENBURG", "052"]'``, as AtlasIO.jl writes
|
|
72
|
+
them (see :func:`district_key_string`). For code written for the old PythonReader/AtlasIO.py."""
|
|
73
|
+
return {district_key_string(k): v for k, v in self.districting.items()}
|
|
74
|
+
|
|
75
|
+
def __repr__(self):
|
|
76
|
+
return "Map(name=%r, weight=%r, %d regions)" % (self.name, self.weight, len(self.districting))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Atlas:
|
|
80
|
+
"""An Atlas open for reading. Iterate over it (or call :meth:`next_map`) to read its maps in order.
|
|
81
|
+
|
|
82
|
+
Attributes: ``description``, ``date``, ``atlas_param_type``, ``map_param_type``, ``weight_type``
|
|
83
|
+
(``"Int64"`` or ``"Float64"``), ``format_version`` (``"1"`` or ``"2"``), ``header`` (the whole header as a
|
|
84
|
+
dict) and ``params`` (the atlas parameters, line 3).
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, f, close_file=True):
|
|
88
|
+
self._f = f
|
|
89
|
+
self._close_file = close_file
|
|
90
|
+
try:
|
|
91
|
+
f.readline() # line 1: banner, ignored
|
|
92
|
+
header_line = f.readline()
|
|
93
|
+
params_line = f.readline()
|
|
94
|
+
except (OSError, EOFError) as e:
|
|
95
|
+
raise AtlasFormatError("not a valid Atlas file: failed to read the header (%s)" % e) from e
|
|
96
|
+
try:
|
|
97
|
+
header = _loads(header_line)
|
|
98
|
+
except ValueError as e:
|
|
99
|
+
raise AtlasFormatError("not a valid Atlas file: the header line (line 2) did not parse as JSON "
|
|
100
|
+
"(%s)" % e) from e
|
|
101
|
+
if not isinstance(header, dict):
|
|
102
|
+
raise AtlasFormatError("not a valid Atlas file: the header line (line 2) is not a JSON object")
|
|
103
|
+
for k in _REQUIRED_HEADER:
|
|
104
|
+
if k not in header:
|
|
105
|
+
raise AtlasFormatError('not a valid Atlas file: the header line (line 2) is missing "%s"' % k)
|
|
106
|
+
for k, v in header.items():
|
|
107
|
+
if not isinstance(v, str):
|
|
108
|
+
raise AtlasFormatError('not a valid Atlas file: the header value of "%s" must be a JSON string, '
|
|
109
|
+
"not %r" % (k, v))
|
|
110
|
+
self.format_version = header.get("formatVersion", "1")
|
|
111
|
+
if self.format_version not in FORMAT_VERSIONS:
|
|
112
|
+
raise AtlasFormatError('unsupported Atlas formatVersion "%s": atlasio %s reads format versions %s. '
|
|
113
|
+
"Upgrade atlasio to read this file."
|
|
114
|
+
% (self.format_version, __version__, " and ".join(FORMAT_VERSIONS)))
|
|
115
|
+
self.header = header
|
|
116
|
+
self.description = header["description"]
|
|
117
|
+
self.date = header["date"]
|
|
118
|
+
self.atlas_param_type = header["atlasParamType"]
|
|
119
|
+
self.map_param_type = header["mapParamType"]
|
|
120
|
+
self.weight_type = header.get("weightType", "Int64")
|
|
121
|
+
try:
|
|
122
|
+
self.params = _loads(params_line)
|
|
123
|
+
except ValueError as e:
|
|
124
|
+
raise AtlasFormatError("not a valid Atlas file: the atlas-parameters line (line 3) did not parse "
|
|
125
|
+
"as JSON (%s)" % e) from e
|
|
126
|
+
|
|
127
|
+
def next_map(self):
|
|
128
|
+
"""The next map, or ``None`` at the end of the file."""
|
|
129
|
+
line = self._f.readline()
|
|
130
|
+
if not line:
|
|
131
|
+
return None
|
|
132
|
+
return _parse_map(line, self.format_version)
|
|
133
|
+
|
|
134
|
+
def __iter__(self):
|
|
135
|
+
while True:
|
|
136
|
+
m = self.next_map()
|
|
137
|
+
if m is None:
|
|
138
|
+
return
|
|
139
|
+
yield m
|
|
140
|
+
|
|
141
|
+
def close(self):
|
|
142
|
+
if self._close_file:
|
|
143
|
+
self._f.close()
|
|
144
|
+
|
|
145
|
+
def __enter__(self):
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
def __exit__(self, *exc):
|
|
149
|
+
self.close()
|
|
150
|
+
|
|
151
|
+
def __repr__(self):
|
|
152
|
+
return "Atlas(description=%r, format_version=%r)" % (self.description, self.format_version)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def open_atlas(source):
|
|
156
|
+
"""Open an Atlas file for reading.
|
|
157
|
+
|
|
158
|
+
``source`` is a path (``.jsonl``, ``.jsonl.gz`` or ``.jsonl.bz2``; the compression is chosen by the
|
|
159
|
+
extension) or an already open file object (text or binary), which is then left open on ``close``.
|
|
160
|
+
"""
|
|
161
|
+
if hasattr(source, "readline"):
|
|
162
|
+
return Atlas(source, close_file=False)
|
|
163
|
+
path = os.fspath(source)
|
|
164
|
+
if path.endswith(".gz"):
|
|
165
|
+
f = gzip.open(path, "rt", encoding="utf-8", newline="\n")
|
|
166
|
+
elif path.endswith(".bz2"):
|
|
167
|
+
f = bz2.open(path, "rt", encoding="utf-8", newline="\n")
|
|
168
|
+
else:
|
|
169
|
+
f = open(path, "r", encoding="utf-8", newline="\n")
|
|
170
|
+
try:
|
|
171
|
+
return Atlas(f)
|
|
172
|
+
except BaseException:
|
|
173
|
+
f.close()
|
|
174
|
+
raise
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def parse_map(line):
|
|
178
|
+
"""Parse one map line, in either format version, into a :class:`Map`."""
|
|
179
|
+
return _parse_map(line, None)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _map_name(x):
|
|
183
|
+
n = x.get("name") if isinstance(x, dict) else None
|
|
184
|
+
return ' (map "%s")' % n if isinstance(n, str) else ""
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _parse_map(line, version):
|
|
188
|
+
try:
|
|
189
|
+
x = _loads(line)
|
|
190
|
+
except ValueError as e:
|
|
191
|
+
raise AtlasFormatError("not a valid Atlas map line: failed to parse as JSON (%s)" % e) from e
|
|
192
|
+
if not isinstance(x, dict):
|
|
193
|
+
raise AtlasFormatError("not a valid Atlas map line: a map line must be a JSON object")
|
|
194
|
+
has_v1, has_v2 = "districting" in x, "assignment" in x
|
|
195
|
+
if not (has_v1 or has_v2):
|
|
196
|
+
raise AtlasFormatError('map line has neither "districting" (v1) nor "assignment" (v2)' + _map_name(x))
|
|
197
|
+
if has_v1 and has_v2:
|
|
198
|
+
raise AtlasFormatError('map line has both "districting" (v1) and "assignment" (v2)' + _map_name(x))
|
|
199
|
+
if version is not None and (version == "2") != has_v2:
|
|
200
|
+
raise AtlasFormatError('map line has %s but the header declares formatVersion "%s"%s; a file holds maps '
|
|
201
|
+
"of one version only" % ('"assignment" (v2)' if has_v2 else '"districting" (v1)',
|
|
202
|
+
version, _map_name(x)))
|
|
203
|
+
for k in ("name", "weight", "data"):
|
|
204
|
+
if k not in x:
|
|
205
|
+
raise AtlasFormatError('not a valid Atlas map line: missing "%s"%s' % (k, _map_name(x)))
|
|
206
|
+
if has_v2:
|
|
207
|
+
districting = _from_assignment(x["assignment"], x)
|
|
208
|
+
else:
|
|
209
|
+
districting = _from_v1(x["districting"], x)
|
|
210
|
+
return Map(x["name"], x["weight"], x["data"], districting)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _from_v1(entries, x):
|
|
214
|
+
if not isinstance(entries, list):
|
|
215
|
+
raise AtlasFormatError('"districting" must be a JSON array' + _map_name(x))
|
|
216
|
+
d = {}
|
|
217
|
+
for entry in entries:
|
|
218
|
+
for k, v in entry.items():
|
|
219
|
+
d[parse_district_key(k)] = v
|
|
220
|
+
return d
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _from_assignment(tree, x):
|
|
224
|
+
if not isinstance(tree, dict):
|
|
225
|
+
raise AtlasFormatError('"assignment" must be a JSON object' + _map_name(x))
|
|
226
|
+
d = {}
|
|
227
|
+
stack = [((), tree)]
|
|
228
|
+
while stack:
|
|
229
|
+
prefix, node = stack.pop()
|
|
230
|
+
for name, v in node.items():
|
|
231
|
+
key = prefix + (name,)
|
|
232
|
+
if type(v) is int: # bool is a subclass of int; it is rejected below
|
|
233
|
+
d[key] = v
|
|
234
|
+
elif isinstance(v, dict):
|
|
235
|
+
if not v:
|
|
236
|
+
raise AtlasFormatError('empty branch at key %r in "assignment": a split region must have at '
|
|
237
|
+
"least one sub-region%s" % (key, _map_name(x)))
|
|
238
|
+
stack.append((key, v))
|
|
239
|
+
else:
|
|
240
|
+
raise AtlasFormatError('the value at key %r in "assignment" is %r; it must be an integer district '
|
|
241
|
+
"or an object of sub-regions%s" % (key, v, _map_name(x)))
|
|
242
|
+
return d
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
_SIMPLE_KEY_PART = re.compile(r'"([^"\\]*)"')
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def parse_district_key(s):
|
|
249
|
+
"""Decode a v1 district-key string such as ``'["MECKLENBURG", "052"]'`` into ``("MECKLENBURG", "052")``."""
|
|
250
|
+
if "\\" not in s:
|
|
251
|
+
# No escapes, so no quote inside a name: every quoted run is one name, whatever the spacing.
|
|
252
|
+
return tuple(_SIMPLE_KEY_PART.findall(s))
|
|
253
|
+
parts = json.loads(s)
|
|
254
|
+
if not (isinstance(parts, list) and all(isinstance(p, str) for p in parts)):
|
|
255
|
+
raise AtlasFormatError("district key %r is not a JSON array of strings" % s)
|
|
256
|
+
return tuple(parts)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def district_key_string(key):
|
|
260
|
+
"""The v1 district-key string for ``key`` exactly as AtlasIO.jl writes it: a JSON-style list with ``", "``
|
|
261
|
+
between names, escaping only ``"`` and ``\\``; e.g. ``("MECKLENBURG", "052")`` -> ``'["MECKLENBURG", "052"]'``."""
|
|
262
|
+
return "[" + ", ".join('"' + p.replace("\\", "\\\\").replace('"', '\\"') + '"' for p in key) + "]"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
from ._write import AtlasWriter, map_json, new_atlas # noqa: E402 (after the definitions they use)
|
|
266
|
+
from ._convert import convert # noqa: E402
|
atlasio/__main__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Command line: ``python -m atlasio convert SRC DST --to 2`` (or ``atlasio convert ...`` once installed)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from . import AtlasFormatError, __version__, convert
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None):
|
|
9
|
+
parser = argparse.ArgumentParser(prog="atlasio", description="Tools for Atlas files (redistricting ensembles).")
|
|
10
|
+
parser.add_argument("--version", action="version", version="atlasio " + __version__)
|
|
11
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
12
|
+
c = sub.add_parser("convert", help="convert an Atlas file between format versions 1 and 2",
|
|
13
|
+
description="Copy SRC to DST, converting every map to format version --to. Only the "
|
|
14
|
+
"header's formatVersion and each map's assignment are rewritten; everything "
|
|
15
|
+
"else is copied byte for byte. Files may be .jsonl, .jsonl.gz or .jsonl.bz2.")
|
|
16
|
+
c.add_argument("src")
|
|
17
|
+
c.add_argument("dst")
|
|
18
|
+
c.add_argument("--to", required=True, choices=["1", "2"], help="target format version")
|
|
19
|
+
args = parser.parse_args(argv)
|
|
20
|
+
try:
|
|
21
|
+
n = convert(args.src, args.dst, args.to)
|
|
22
|
+
except (AtlasFormatError, ValueError, OSError) as e:
|
|
23
|
+
print("atlasio convert: %s" % e, file=sys.stderr)
|
|
24
|
+
return 1
|
|
25
|
+
print("converted %d maps to format v%s: %s" % (n, args.to, args.dst))
|
|
26
|
+
return 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if __name__ == "__main__":
|
|
30
|
+
sys.exit(main())
|
atlasio/_convert.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Convert Atlas files between format versions 1 and 2 (atlas_format.md).
|
|
2
|
+
|
|
3
|
+
Mirrors AtlasIO.jl's convertAtlas: only the header's formatVersion and each map's assignment field are rewritten;
|
|
4
|
+
the banner, the atlas parameters and each map's name, weight and data are copied byte for byte.
|
|
5
|
+
"""
|
|
6
|
+
import bz2
|
|
7
|
+
import gzip
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from ._write import _assignment_json, _districting_v1, _version
|
|
13
|
+
|
|
14
|
+
_FIELD = {"1": "districting", "2": "assignment"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _open_text(path, mode):
|
|
18
|
+
path = os.fspath(path)
|
|
19
|
+
if path.endswith(".gz"):
|
|
20
|
+
return gzip.open(path, mode + "t", encoding="utf-8", newline="\n")
|
|
21
|
+
if path.endswith(".bz2"):
|
|
22
|
+
return bz2.open(path, mode + "t", encoding="utf-8", newline="\n")
|
|
23
|
+
return open(path, mode, encoding="utf-8", newline="\n")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def convert(src, dst, to):
|
|
27
|
+
"""Copy the Atlas file ``src`` to ``dst``, converting every map to format version ``to`` (1 or 2).
|
|
28
|
+
|
|
29
|
+
Either file may be plain, ``.gz`` or ``.bz2`` (chosen by extension). Returns the number of maps.
|
|
30
|
+
|
|
31
|
+
Only what the version changes is rewritten: the header's ``formatVersion`` (added for v2, removed for v1)
|
|
32
|
+
and each map's assignment field (``districting`` in v1, ``assignment`` in v2). The banner, the atlas
|
|
33
|
+
parameters and each map's name, weight and data are copied byte for byte. v2 trees are written with sorted
|
|
34
|
+
names; v1 entries in sorted key order, with keys in the form AtlasIO.jl writes. Every line ends with a
|
|
35
|
+
newline. Converting is lossless: converting back gives the same districting for every map.
|
|
36
|
+
|
|
37
|
+
Raises ``atlasio.AtlasFormatError`` naming the line and map for anything that cannot be converted (a map
|
|
38
|
+
line that does not match the header's version, a districting v2 cannot hold, or a map line whose assignment
|
|
39
|
+
is not its last field); ``dst`` is then removed.
|
|
40
|
+
"""
|
|
41
|
+
from . import AtlasFormatError # noqa: F401 (imported here to avoid a cycle at import time)
|
|
42
|
+
|
|
43
|
+
to = _version(to)
|
|
44
|
+
if os.path.abspath(os.fspath(src)) == os.path.abspath(os.fspath(dst)):
|
|
45
|
+
raise ValueError("convert: src and dst are the same file: %s" % (src,))
|
|
46
|
+
n = 0
|
|
47
|
+
with _open_text(src, "r") as fin:
|
|
48
|
+
banner = _strip_newline(fin.readline())
|
|
49
|
+
header = _strip_newline(fin.readline())
|
|
50
|
+
params = _strip_newline(fin.readline())
|
|
51
|
+
frm, new_header = _convert_header(header, to)
|
|
52
|
+
try:
|
|
53
|
+
with _open_text(dst, "w") as fout:
|
|
54
|
+
fout.write(banner + "\n" + new_header + "\n" + params + "\n")
|
|
55
|
+
lineno = 3
|
|
56
|
+
for line in fin:
|
|
57
|
+
lineno += 1
|
|
58
|
+
fout.write(_convert_map_line(_strip_newline(line), frm, to, lineno))
|
|
59
|
+
n += 1
|
|
60
|
+
except BaseException:
|
|
61
|
+
try:
|
|
62
|
+
os.remove(dst)
|
|
63
|
+
except OSError:
|
|
64
|
+
pass
|
|
65
|
+
raise
|
|
66
|
+
return n
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _strip_newline(line):
|
|
70
|
+
if line.endswith("\n"):
|
|
71
|
+
line = line[:-1]
|
|
72
|
+
if line.endswith("\r"):
|
|
73
|
+
line = line[:-1]
|
|
74
|
+
return line
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_VERSION_FIELD = r'"formatVersion"\s*:\s*"[^"\\]*"'
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _convert_header(line, to):
|
|
81
|
+
from . import AtlasFormatError
|
|
82
|
+
try:
|
|
83
|
+
h = json.loads(line)
|
|
84
|
+
except ValueError as e:
|
|
85
|
+
raise AtlasFormatError("not a valid Atlas file: the header line (line 2) did not parse as JSON (%s)" % e)
|
|
86
|
+
if not isinstance(h, dict):
|
|
87
|
+
raise AtlasFormatError("not a valid Atlas file: the header line (line 2) is not a JSON object")
|
|
88
|
+
for k, v in h.items():
|
|
89
|
+
if not isinstance(v, str):
|
|
90
|
+
raise AtlasFormatError('not a valid Atlas file: the header value of "%s" must be a JSON string' % k)
|
|
91
|
+
frm = h.get("formatVersion", "1")
|
|
92
|
+
if frm not in ("1", "2"):
|
|
93
|
+
raise AtlasFormatError('unsupported Atlas formatVersion "%s": upgrade atlasio' % frm)
|
|
94
|
+
if frm == to:
|
|
95
|
+
return frm, line
|
|
96
|
+
had = "formatVersion" in h
|
|
97
|
+
if to == "1":
|
|
98
|
+
del h["formatVersion"]
|
|
99
|
+
else:
|
|
100
|
+
h["formatVersion"] = to
|
|
101
|
+
# Edit just that field in the original text, so the rest of the header keeps its exact bytes; keep the edit
|
|
102
|
+
# only if it parses to exactly the intended header (same fields, values and order).
|
|
103
|
+
edited = _edit_header_version(line, had, to)
|
|
104
|
+
if edited is not None:
|
|
105
|
+
try:
|
|
106
|
+
if list(json.loads(edited).items()) == list(h.items()):
|
|
107
|
+
return frm, edited
|
|
108
|
+
except ValueError:
|
|
109
|
+
pass
|
|
110
|
+
return frm, json.dumps(h, ensure_ascii=False, separators=(",", ":"))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _edit_header_version(line, had, to):
|
|
114
|
+
if to == "2":
|
|
115
|
+
if had:
|
|
116
|
+
return re.sub(_VERSION_FIELD, '"formatVersion":"2"', line, count=1)
|
|
117
|
+
s = line.rstrip()
|
|
118
|
+
if not s.endswith("}"):
|
|
119
|
+
return None
|
|
120
|
+
body = s[:-1].rstrip()
|
|
121
|
+
return body + ("" if body.endswith("{") else ",") + '"formatVersion":"2"}'
|
|
122
|
+
for pat in (r"\s*,\s*" + _VERSION_FIELD, _VERSION_FIELD + r"\s*,?\s*"):
|
|
123
|
+
if re.search(pat, line):
|
|
124
|
+
return re.sub(pat, "", line, count=1)
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _convert_map_line(line, frm, to, lineno):
|
|
129
|
+
from . import AtlasFormatError, _from_assignment, _from_v1
|
|
130
|
+
if frm == to:
|
|
131
|
+
return line + "\n"
|
|
132
|
+
try:
|
|
133
|
+
x = json.loads(line)
|
|
134
|
+
except ValueError as e:
|
|
135
|
+
raise AtlasFormatError("line %d: not a valid Atlas map line: failed to parse as JSON (%s)" % (lineno, e))
|
|
136
|
+
if not isinstance(x, dict):
|
|
137
|
+
raise AtlasFormatError("line %d: not a valid Atlas map line: a map line must be a JSON object" % lineno)
|
|
138
|
+
name = x.get("name") if isinstance(x.get("name"), str) else None
|
|
139
|
+
where = "line %d%s" % (lineno, ' (map "%s")' % name if name is not None else "")
|
|
140
|
+
field, other = _FIELD[frm], _FIELD[to]
|
|
141
|
+
if field not in x:
|
|
142
|
+
raise AtlasFormatError('%s: the header declares formatVersion "%s" but the map line has no "%s"%s'
|
|
143
|
+
% (where, frm, field, ' (it has "%s")' % other if other in x else ""))
|
|
144
|
+
if other in x:
|
|
145
|
+
raise AtlasFormatError('%s: the map line has both "districting" and "assignment"' % where)
|
|
146
|
+
try:
|
|
147
|
+
d = _from_v1(x[field], x) if frm == "1" else _from_assignment(x[field], x)
|
|
148
|
+
except AtlasFormatError as e:
|
|
149
|
+
raise AtlasFormatError("%s: %s" % (where, e))
|
|
150
|
+
except (AttributeError, TypeError, ValueError) as e:
|
|
151
|
+
raise AtlasFormatError("%s: not a valid Atlas map line: %s" % (where, e))
|
|
152
|
+
start = _last_top_level_key_start(line)
|
|
153
|
+
key = '"%s"' % field
|
|
154
|
+
if start < 0 or line[start:start + len(key)] != key:
|
|
155
|
+
raise AtlasFormatError('%s: the assignment ("%s") must be the map line\'s last field, as atlas_format.md '
|
|
156
|
+
"requires; convert only rewrites that field" % (where, field))
|
|
157
|
+
if to == "2":
|
|
158
|
+
new = '"assignment":' + _assignment_json(d, "%s: cannot convert to v2: " % where)
|
|
159
|
+
else:
|
|
160
|
+
new = '"districting":' + _districting_v1(d)
|
|
161
|
+
return line[:start] + new + "}\n"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _last_top_level_key_start(s):
|
|
165
|
+
"""Index of the opening quote of the last key of the top-level JSON object in ``s``, or -1."""
|
|
166
|
+
depth = 0
|
|
167
|
+
instr = esc = expect_key = False
|
|
168
|
+
last = -1
|
|
169
|
+
for i, c in enumerate(s):
|
|
170
|
+
if instr:
|
|
171
|
+
if esc:
|
|
172
|
+
esc = False
|
|
173
|
+
elif c == "\\":
|
|
174
|
+
esc = True
|
|
175
|
+
elif c == '"':
|
|
176
|
+
instr = False
|
|
177
|
+
elif c == '"':
|
|
178
|
+
instr = True
|
|
179
|
+
if depth == 1 and expect_key:
|
|
180
|
+
last = i
|
|
181
|
+
expect_key = False
|
|
182
|
+
elif c in "{[":
|
|
183
|
+
depth += 1
|
|
184
|
+
expect_key = depth == 1 and c == "{"
|
|
185
|
+
elif c in "}]":
|
|
186
|
+
depth -= 1
|
|
187
|
+
expect_key = False
|
|
188
|
+
elif c == ",":
|
|
189
|
+
expect_key = depth == 1
|
|
190
|
+
elif c not in " \t\n\r":
|
|
191
|
+
expect_key = False
|
|
192
|
+
return last
|
atlasio/_write.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Write Atlas files (atlas_format.md), format version 1 or 2, laid out as AtlasIO.jl's newAtlas/addMap write them.
|
|
2
|
+
|
|
3
|
+
Also holds the districting encoders that ``convert`` shares, so a map written here and the same map converted (or
|
|
4
|
+
written by AtlasIO.jl) have byte-identical assignments.
|
|
5
|
+
"""
|
|
6
|
+
import bz2
|
|
7
|
+
import datetime
|
|
8
|
+
import gzip
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import numbers
|
|
13
|
+
import operator
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
|
|
17
|
+
from . import AtlasFormatError, Map, district_key_string
|
|
18
|
+
|
|
19
|
+
#: Line 1 of every Atlas file, exactly as AtlasIO.jl writes it.
|
|
20
|
+
BANNER = ("This is an Atlas for Redistricting Maps. See "
|
|
21
|
+
"'https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md' for more information about the format.")
|
|
22
|
+
|
|
23
|
+
#: The parameter type name AtlasIO.jl writes for plain dictionaries (Julia's ``string(Dict{String,Any})``).
|
|
24
|
+
DEFAULT_PARAM_TYPE = "Dict{String, Any}"
|
|
25
|
+
|
|
26
|
+
WEIGHT_TYPES = ("Int64", "Float64")
|
|
27
|
+
|
|
28
|
+
_INT64_MIN, _INT64_MAX = -2 ** 63, 2 ** 63 - 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _version(v):
|
|
32
|
+
"""Normalize a format version given as 1, 2, '1' or '2' to the header's string form."""
|
|
33
|
+
s = v if isinstance(v, str) else (str(v) if isinstance(v, int) and not isinstance(v, bool) else "")
|
|
34
|
+
if s not in ("1", "2"):
|
|
35
|
+
raise ValueError("format version must be 1 or 2 (or '1' or '2'), got %r" % (v,))
|
|
36
|
+
return s
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------------------------------------------------------
|
|
40
|
+
# Encoders (shared with convert)
|
|
41
|
+
|
|
42
|
+
def _districting_v1(d):
|
|
43
|
+
"""The v1 ``districting`` array for ``d`` ({key tuple: district}), entries in sorted key order."""
|
|
44
|
+
return "[" + ",".join("{%s:%d}" % (json.dumps(district_key_string(k), ensure_ascii=False), d[k])
|
|
45
|
+
for k in sorted(d)) + "]"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _assignment_json(d, err, hint=""):
|
|
49
|
+
"""The v2 ``assignment`` tree for ``d`` ({key tuple: district}), names sorted at every level.
|
|
50
|
+
|
|
51
|
+
A districting v2 cannot hold raises AtlasFormatError: ``err`` starts the message, ``hint`` ends it.
|
|
52
|
+
"""
|
|
53
|
+
tree = {}
|
|
54
|
+
for k, v in d.items():
|
|
55
|
+
if not k:
|
|
56
|
+
raise AtlasFormatError("%sthe district key () is empty; a v2 key names at least one region%s"
|
|
57
|
+
% (err, hint))
|
|
58
|
+
node = tree
|
|
59
|
+
for i, part in enumerate(k[:-1]):
|
|
60
|
+
child = node.setdefault(part, {})
|
|
61
|
+
if not isinstance(child, dict):
|
|
62
|
+
_prefix_error(err, hint, k[:i + 1], k)
|
|
63
|
+
node = child
|
|
64
|
+
if k[-1] in node:
|
|
65
|
+
_prefix_error(err, hint, k, _some_key_under(k, node[k[-1]]))
|
|
66
|
+
node[k[-1]] = v
|
|
67
|
+
# sort_keys sorts by code point, the UTF-8 byte order the spec asks for
|
|
68
|
+
return json.dumps(tree, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _some_key_under(prefix, node):
|
|
72
|
+
while isinstance(node, dict):
|
|
73
|
+
name = min(node)
|
|
74
|
+
prefix, node = prefix + (name,), node[name]
|
|
75
|
+
return prefix
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _prefix_error(err, hint, short, long):
|
|
79
|
+
raise AtlasFormatError("%sthe key %r is a prefix of the key %r, so the region would be both whole and split "
|
|
80
|
+
"(rule 1 of atlas_format.md)%s" % (err, tuple(short), tuple(long), hint))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _json_default(o):
|
|
84
|
+
# numpy scalars and arrays (and anything else with .tolist()) become plain Python values
|
|
85
|
+
if hasattr(o, "tolist"):
|
|
86
|
+
return o.tolist()
|
|
87
|
+
raise TypeError("%s is not JSON serializable" % type(o).__name__)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _dumps(x):
|
|
91
|
+
return json.dumps(x, ensure_ascii=False, separators=(",", ":"), allow_nan=False, default=_json_default)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------------------------------------------
|
|
95
|
+
# Checking what the caller passes
|
|
96
|
+
|
|
97
|
+
def _for_map(name):
|
|
98
|
+
return 'map "%s": ' % name if name else ""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _check_districting(d, name):
|
|
102
|
+
"""``d`` as {tuple of str: int}, or TypeError/ValueError saying what is wrong."""
|
|
103
|
+
if not isinstance(d, Mapping):
|
|
104
|
+
raise TypeError("%sthe districting must be a dict of {key tuple: district}, not %s"
|
|
105
|
+
% (_for_map(name), type(d).__name__))
|
|
106
|
+
out = {}
|
|
107
|
+
for k, v in d.items():
|
|
108
|
+
if type(k) is not tuple:
|
|
109
|
+
if isinstance(k, (str, bytes)):
|
|
110
|
+
raise TypeError("%sdistrict key %r is a string; keys are tuples of names from the coarsest level "
|
|
111
|
+
"down, e.g. ('WAKE',) or ('MECKLENBURG', '052')" % (_for_map(name), k))
|
|
112
|
+
try:
|
|
113
|
+
k = tuple(k)
|
|
114
|
+
except TypeError:
|
|
115
|
+
raise TypeError("%sdistrict key %r is not a tuple of names" % (_for_map(name), k)) from None
|
|
116
|
+
for p in k:
|
|
117
|
+
if not isinstance(p, str):
|
|
118
|
+
raise TypeError("%sdistrict key %r: every name must be a string, not %r" % (_for_map(name), k, p))
|
|
119
|
+
if type(v) is not int:
|
|
120
|
+
if isinstance(v, bool) or not hasattr(v, "__index__"):
|
|
121
|
+
raise TypeError("%sthe district of %r is %r; it must be an integer" % (_for_map(name), k, v))
|
|
122
|
+
v = operator.index(v) # e.g. a numpy integer
|
|
123
|
+
if not _INT64_MIN <= v <= _INT64_MAX:
|
|
124
|
+
raise ValueError("%sthe district of %r is %d, beyond a 64-bit integer" % (_for_map(name), k, v))
|
|
125
|
+
out[k] = v
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _check_weight(w, weight_type, name):
|
|
130
|
+
if weight_type == "Int64":
|
|
131
|
+
if isinstance(w, bool) or not hasattr(w, "__index__"):
|
|
132
|
+
raise TypeError("%sthe weight is %r, but this atlas's weight_type is Int64 (pass an integer, or use "
|
|
133
|
+
"weight_type='Float64')" % (_for_map(name), w))
|
|
134
|
+
w = operator.index(w)
|
|
135
|
+
if not _INT64_MIN <= w <= _INT64_MAX:
|
|
136
|
+
raise ValueError("%sthe weight %d is beyond a 64-bit integer" % (_for_map(name), w))
|
|
137
|
+
return w
|
|
138
|
+
if isinstance(w, bool) or not isinstance(w, numbers.Real):
|
|
139
|
+
raise TypeError("%sthe weight must be a number, not %r" % (_for_map(name), w))
|
|
140
|
+
w = float(w)
|
|
141
|
+
if not math.isfinite(w):
|
|
142
|
+
raise ValueError("%sthe weight is %r; JSON has no NaN or infinity" % (_for_map(name), w))
|
|
143
|
+
return w
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def map_json(m, format_version=1, weight_type=None):
|
|
147
|
+
"""The JSON line (without the newline) for :class:`Map` ``m`` in format version ``format_version``, as
|
|
148
|
+
:meth:`AtlasWriter.add_map` writes it: fields ``name``, ``weight``, ``data`` and then the assignment
|
|
149
|
+
(``districting`` in v1, ``assignment`` in v2). ``weight_type`` (``"Int64"`` or ``"Float64"``) checks the
|
|
150
|
+
weight and writes a Float64 weight as a float; by default an integer weight is written as Int64 and a float
|
|
151
|
+
one as Float64.
|
|
152
|
+
"""
|
|
153
|
+
return _map_json(m.name, m.districting, m.weight, m.data, _version(format_version), weight_type)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _map_json(name, districting, weight, data, version, weight_type):
|
|
157
|
+
if not isinstance(name, str):
|
|
158
|
+
raise TypeError("the map name must be a string, not %r" % (name,))
|
|
159
|
+
if weight_type is None:
|
|
160
|
+
weight_type = "Float64" if isinstance(weight, float) else "Int64"
|
|
161
|
+
weight = _check_weight(weight, weight_type, name)
|
|
162
|
+
d = _check_districting(districting, name)
|
|
163
|
+
if version == "2":
|
|
164
|
+
field = '"assignment":' + _assignment_json(d, "cannot write format v2: " + _for_map(name),
|
|
165
|
+
". Write format v1 or fix the districting.")
|
|
166
|
+
else:
|
|
167
|
+
field = '"districting":' + _districting_v1(d)
|
|
168
|
+
try:
|
|
169
|
+
data_json = _dumps({} if data is None else data)
|
|
170
|
+
except ValueError as e: # NaN or infinity
|
|
171
|
+
raise ValueError("%sthe map data cannot be written as JSON: %s" % (_for_map(name), e)) from None
|
|
172
|
+
return '{"name":%s,"weight":%s,"data":%s,%s}' % (_dumps(name), _dumps(weight), data_json, field)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------------------------------------------------------
|
|
176
|
+
# The writer
|
|
177
|
+
|
|
178
|
+
class AtlasWriter:
|
|
179
|
+
"""An Atlas open for writing, as returned by :func:`new_atlas`; the header is already written. Add maps with
|
|
180
|
+
:meth:`add_map` or :meth:`add_maps`, then :meth:`close` (or use it in a ``with`` block).
|
|
181
|
+
|
|
182
|
+
Attributes: ``format_version`` (``"1"`` or ``"2"``), ``weight_type``, ``header`` (the header written, as a
|
|
183
|
+
dict), ``params`` and ``count`` (the number of maps written so far).
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
def __init__(self, f, close, header, params):
|
|
187
|
+
self._f = f
|
|
188
|
+
self._close = close
|
|
189
|
+
self.header = header
|
|
190
|
+
self.params = params
|
|
191
|
+
self.format_version = header.get("formatVersion", "1")
|
|
192
|
+
self.weight_type = header["weightType"]
|
|
193
|
+
self.count = 0
|
|
194
|
+
f.write(_dumps(BANNER) + "\n" + _dumps(header) + "\n")
|
|
195
|
+
try:
|
|
196
|
+
f.write(_dumps(params) + "\n")
|
|
197
|
+
except ValueError as e:
|
|
198
|
+
raise ValueError("the atlas parameters cannot be written as JSON: %s" % e) from None
|
|
199
|
+
|
|
200
|
+
def add_map(self, map_or_name, districting=None, weight=1, data=None):
|
|
201
|
+
"""Write one map: ``add_map(name, districting, weight=1, data=None)``, or ``add_map(m)`` for a
|
|
202
|
+
:class:`Map` (such as one read from another atlas).
|
|
203
|
+
|
|
204
|
+
``districting`` maps each region's key, a tuple of names from the coarsest level down such as
|
|
205
|
+
``("WAKE",)`` or ``("MECKLENBURG", "052")``, to its integer district. ``data`` is any JSON-serializable
|
|
206
|
+
value (numpy numbers and arrays are converted); ``None`` writes ``{}``. In format v2 a districting with a
|
|
207
|
+
region both whole and split (one key a prefix of another) raises :class:`AtlasFormatError`.
|
|
208
|
+
"""
|
|
209
|
+
if self._f is None:
|
|
210
|
+
raise ValueError("add_map: the atlas is closed")
|
|
211
|
+
if isinstance(map_or_name, Map):
|
|
212
|
+
if districting is not None:
|
|
213
|
+
raise TypeError("add_map(m) takes a Map alone; pass add_map(name, districting, ...) otherwise")
|
|
214
|
+
m = map_or_name
|
|
215
|
+
name, districting, weight, data = m.name, m.districting, m.weight, m.data
|
|
216
|
+
else:
|
|
217
|
+
name = map_or_name
|
|
218
|
+
if districting is None:
|
|
219
|
+
raise TypeError("add_map(name, districting, weight=1, data=None): the districting is missing")
|
|
220
|
+
line = _map_json(name, districting, weight, data, self.format_version, self.weight_type)
|
|
221
|
+
self._f.write(line + "\n")
|
|
222
|
+
self.count += 1
|
|
223
|
+
|
|
224
|
+
def add_maps(self, maps):
|
|
225
|
+
"""Write each :class:`Map` in ``maps``, in order."""
|
|
226
|
+
for m in maps:
|
|
227
|
+
self.add_map(m)
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def closed(self):
|
|
231
|
+
return self._f is None
|
|
232
|
+
|
|
233
|
+
def close(self):
|
|
234
|
+
if self._f is not None:
|
|
235
|
+
f, self._f = self._f, None
|
|
236
|
+
self._close(f)
|
|
237
|
+
|
|
238
|
+
def __enter__(self):
|
|
239
|
+
return self
|
|
240
|
+
|
|
241
|
+
def __exit__(self, *exc):
|
|
242
|
+
self.close()
|
|
243
|
+
|
|
244
|
+
def __repr__(self):
|
|
245
|
+
return "AtlasWriter(format_version=%r, %d maps%s)" % (self.format_version, self.count,
|
|
246
|
+
", closed" if self.closed else "")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def new_atlas(dest, description=None, params=None, *, date=None, atlas_param_type=None, map_param_type=None,
|
|
250
|
+
weight_type=None, format_version=None, like=None):
|
|
251
|
+
"""Create an Atlas file and write its header; returns an :class:`AtlasWriter` to add maps to.
|
|
252
|
+
|
|
253
|
+
``dest`` is a path (``.jsonl``, ``.jsonl.gz`` or ``.jsonl.bz2``; the compression is chosen by the extension)
|
|
254
|
+
or an open file object (text or binary), which is left open on ``close``.
|
|
255
|
+
|
|
256
|
+
The header: ``description`` (default ``""``), ``date`` (default now), ``atlas_param_type`` and
|
|
257
|
+
``map_param_type`` (names of the types the parameters and map data hold; default ``"Dict{String, Any}"``, as
|
|
258
|
+
AtlasIO.jl writes for a dict) and ``weight_type`` (``"Int64"``, the default, or ``"Float64"``). ``params``
|
|
259
|
+
(default ``{}``) is the atlas parameters, line 3. ``format_version`` is 1 (the default, as in AtlasIO.jl) or
|
|
260
|
+
2; v2 adds ``"formatVersion":"2"`` to the header and writes each map's assignment as a tree.
|
|
261
|
+
|
|
262
|
+
``like`` is an open :class:`Atlas` whose header and parameters (and format version) are copied, for writing a
|
|
263
|
+
modified copy of an atlas; any argument given explicitly overrides what it supplies.
|
|
264
|
+
"""
|
|
265
|
+
def pick(value, attr, default):
|
|
266
|
+
if value is not None:
|
|
267
|
+
return value
|
|
268
|
+
return getattr(like, attr) if like is not None else default
|
|
269
|
+
|
|
270
|
+
version = _version(pick(format_version, "format_version", 1))
|
|
271
|
+
header = {
|
|
272
|
+
"description": pick(description, "description", ""),
|
|
273
|
+
"date": pick(date, "date", None) or datetime.datetime.now().isoformat(timespec="milliseconds"),
|
|
274
|
+
"atlasParamType": pick(atlas_param_type, "atlas_param_type", DEFAULT_PARAM_TYPE),
|
|
275
|
+
"mapParamType": pick(map_param_type, "map_param_type", DEFAULT_PARAM_TYPE),
|
|
276
|
+
"weightType": pick(weight_type, "weight_type", "Int64"),
|
|
277
|
+
}
|
|
278
|
+
if version != "1":
|
|
279
|
+
header["formatVersion"] = version
|
|
280
|
+
for k, v in header.items():
|
|
281
|
+
if not isinstance(v, str):
|
|
282
|
+
raise TypeError("new_atlas: the header value %s must be a string, not %r" % (k, v))
|
|
283
|
+
if header["weightType"] not in WEIGHT_TYPES:
|
|
284
|
+
raise ValueError("new_atlas: weight_type must be 'Int64' or 'Float64', not %r" % header["weightType"])
|
|
285
|
+
params = pick(params, "params", {})
|
|
286
|
+
|
|
287
|
+
path = None
|
|
288
|
+
if hasattr(dest, "write"):
|
|
289
|
+
if isinstance(dest, io.TextIOBase):
|
|
290
|
+
f, close = dest, lambda f: f.flush()
|
|
291
|
+
else:
|
|
292
|
+
f = io.TextIOWrapper(dest, encoding="utf-8", newline="\n", write_through=True)
|
|
293
|
+
close = lambda f: (f.flush(), f.detach())
|
|
294
|
+
else:
|
|
295
|
+
path = os.fspath(dest)
|
|
296
|
+
opener = gzip.open if path.endswith(".gz") else bz2.open if path.endswith(".bz2") else None
|
|
297
|
+
f = (opener(path, "wt", encoding="utf-8", newline="\n") if opener
|
|
298
|
+
else open(path, "w", encoding="utf-8", newline="\n"))
|
|
299
|
+
close = lambda f: f.close()
|
|
300
|
+
try:
|
|
301
|
+
return AtlasWriter(f, close, header, params)
|
|
302
|
+
except BaseException:
|
|
303
|
+
close(f)
|
|
304
|
+
if path is not None: # the header could not be written: leave no half-written file
|
|
305
|
+
try:
|
|
306
|
+
os.remove(path)
|
|
307
|
+
except OSError:
|
|
308
|
+
pass
|
|
309
|
+
raise
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: AtlasIO
|
|
3
|
+
Version: 0.2.4
|
|
4
|
+
Summary: Read and write Atlas files (ensembles of redistricting maps), format versions 1 and 2, and convert between them
|
|
5
|
+
Author-email: Jonathan Mattingly <jonathan.mattingly@duke.edu>, Gregory Herschlag <Gregory.Herschlag@duke.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jonmjonm/AtlasIO.jl
|
|
8
|
+
Project-URL: Format, https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md
|
|
9
|
+
Project-URL: Changelog, https://github.com/jonmjonm/AtlasIO.jl/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: redistricting,gerrymandering,districting,ensemble,atlas
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Provides-Extra: fast
|
|
20
|
+
Requires-Dist: orjson; extra == "fast"
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest; extra == "test"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# atlasio (Python)
|
|
26
|
+
|
|
27
|
+
Read [Atlas files](https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md), the format the Duke
|
|
28
|
+
Quantifying Gerrymandering group's samplers (Cycle Walk, Metropolized Forest Recom) use to store ensembles of
|
|
29
|
+
redistricting maps. Reads and writes format versions 1 and 2, plain or compressed (`.jsonl`, `.jsonl.gz`, `.jsonl.bz2`),
|
|
30
|
+
and converts files between the two versions, compatible with [AtlasIO.jl](https://github.com/jonmjonm/AtlasIO.jl)
|
|
31
|
+
(Julia).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
pip install atlasio
|
|
36
|
+
|
|
37
|
+
or, from a release tag of the AtlasIO.jl repository (needs git):
|
|
38
|
+
|
|
39
|
+
pip install "atlasio @ git+https://github.com/jonmjonm/AtlasIO.jl@v0.2.4#subdirectory=python"
|
|
40
|
+
|
|
41
|
+
The package's version always equals AtlasIO.jl's: both are released together from one tag.
|
|
42
|
+
|
|
43
|
+
It needs only the Python standard library (Python 3.9 or later; tested on 3.11 to 3.14). With `pip install orjson` (or the `fast` extra) it
|
|
44
|
+
parses lines faster.
|
|
45
|
+
|
|
46
|
+
## Use
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import atlasio
|
|
50
|
+
|
|
51
|
+
with atlasio.open_atlas("atlas.jsonl.gz") as atlas:
|
|
52
|
+
print(atlas.description, atlas.date, atlas.format_version)
|
|
53
|
+
print(atlas.params) # the atlas parameters (line 3)
|
|
54
|
+
for m in atlas:
|
|
55
|
+
m.name, m.weight, m.data
|
|
56
|
+
m.districting # {("WAKE",): 3, ("MECKLENBURG", "052"): 13, ...}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
District keys are tuples of names from the coarsest level down, as in AtlasIO.jl, whichever format version the
|
|
60
|
+
file uses. `m.raw_districting()` gives the same districting with v1-style string keys
|
|
61
|
+
(`'["MECKLENBURG", "052"]'`), for code written for the original `PythonReader/AtlasIO.py`.
|
|
62
|
+
|
|
63
|
+
Invalid files, a `formatVersion` this version does not know, and maps that break the format's rules raise
|
|
64
|
+
`atlasio.AtlasFormatError` (a `ValueError`).
|
|
65
|
+
|
|
66
|
+
The full API is in [function_calls.md](https://github.com/jonmjonm/AtlasIO.jl/blob/main/function_calls.md).
|
|
67
|
+
|
|
68
|
+
## Write
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
with atlasio.new_atlas("out.jsonl.gz", description="my ensemble", params={"districts": 14}) as out:
|
|
72
|
+
out.add_map("map1", {("WAKE",): 3, ("MECKLENBURG", "052"): 13}, weight=1, data={"score": 0.5})
|
|
73
|
+
out.add_map(m) # or a Map, e.g. one read from another atlas
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`new_atlas(dest, description="", params={}, *, date=now, atlas_param_type, map_param_type, weight_type="Int64",
|
|
77
|
+
format_version=1, like=None)`. The compression is chosen by the extension; `dest` can also be an open file
|
|
78
|
+
object. `format_version=2` writes v2 (v1 is the default, as in AtlasIO.jl). `like=atlas` copies an open atlas's
|
|
79
|
+
header and parameters, for writing a modified copy; explicit arguments override it.
|
|
80
|
+
|
|
81
|
+
District keys are tuples of names and districts integers. Map data can be anything JSON can hold; numpy numbers
|
|
82
|
+
and arrays are converted. NaN and infinity are refused, since JSON has neither. A map that cannot be written
|
|
83
|
+
raises before any of it is written, so the file keeps every map written so far. In v2, a region both whole and
|
|
84
|
+
split (one key a prefix of another) raises `atlasio.AtlasFormatError`.
|
|
85
|
+
|
|
86
|
+
The output is laid out exactly as AtlasIO.jl writes it: the same banner, header and field order, and
|
|
87
|
+
byte-identical v2 assignments; only floats may be spelled differently (`1e-07` for Julia's `1.0e-7`).
|
|
88
|
+
|
|
89
|
+
## Convert between format versions
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
python -m atlasio convert atlas.jsonl.gz atlas_v2.jsonl.gz --to 2 # or: atlasio convert ...
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
or `atlasio.convert("atlas.jsonl.gz", "atlas_v2.jsonl.gz", to=2)`. Only the header's `formatVersion` and each
|
|
96
|
+
map's assignment are rewritten; everything else is copied byte for byte, and converting back gives the same
|
|
97
|
+
districting for every map. A districting v2 cannot hold (a region both whole and split) stops the conversion
|
|
98
|
+
with an error naming the line and map. The output is byte-identical to AtlasIO.jl's `convertAtlas`.
|
|
99
|
+
|
|
100
|
+
## Tests
|
|
101
|
+
|
|
102
|
+
From the repository root: `pip install ./python pytest && python -m pytest python/tests`.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
atlasio/__init__.py,sha256=pS438O4129FC9y4UvTlRZlRkiTP0e_xZ7xM5oz7IdF8,11243
|
|
2
|
+
atlasio/__main__.py,sha256=7ftm0RbJbCSb4J2t9FRTVKyOEk_2qhW5ldC16gIo7js,1421
|
|
3
|
+
atlasio/_convert.py,sha256=WU9867TfeG0F-MchxlyRwkF-p4flu3WhHiJXaRrV0h0,7748
|
|
4
|
+
atlasio/_write.py,sha256=fmrkpa_bdAdTLIvnso5X-tmS3KtFVXDIDDoCf7nQyCM,14037
|
|
5
|
+
atlasio-0.2.4.dist-info/licenses/LICENSE,sha256=sjloovwcKtkCB-mUv-KXiT0UkuX9ft4mX0D6uvYLklw,1094
|
|
6
|
+
atlasio-0.2.4.dist-info/METADATA,sha256=4-uVGYOiacIyobxGU5n43SWuq-s7OI4p4YRtQNQWNdA,4943
|
|
7
|
+
atlasio-0.2.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
atlasio-0.2.4.dist-info/entry_points.txt,sha256=z_wkMPef0TuSaHYt_5v987sPr8CpuA7aJj5mDX9o0mo,50
|
|
9
|
+
atlasio-0.2.4.dist-info/top_level.txt,sha256=UrjiQgpeAk0gSlrxqV-l_eysP-h34ZkKS3dn64vpZRs,8
|
|
10
|
+
atlasio-0.2.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020, Jonathan Mattingly and Greg Herschlag
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
atlasio
|