AtlasIO 0.2.4__tar.gz

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-0.2.4/LICENSE ADDED
@@ -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.
atlasio-0.2.4/PKG-INFO ADDED
@@ -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,78 @@
1
+ # atlasio (Python)
2
+
3
+ Read [Atlas files](https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md), the format the Duke
4
+ Quantifying Gerrymandering group's samplers (Cycle Walk, Metropolized Forest Recom) use to store ensembles of
5
+ redistricting maps. Reads and writes format versions 1 and 2, plain or compressed (`.jsonl`, `.jsonl.gz`, `.jsonl.bz2`),
6
+ and converts files between the two versions, compatible with [AtlasIO.jl](https://github.com/jonmjonm/AtlasIO.jl)
7
+ (Julia).
8
+
9
+ ## Install
10
+
11
+ pip install atlasio
12
+
13
+ or, from a release tag of the AtlasIO.jl repository (needs git):
14
+
15
+ pip install "atlasio @ git+https://github.com/jonmjonm/AtlasIO.jl@v0.2.4#subdirectory=python"
16
+
17
+ The package's version always equals AtlasIO.jl's: both are released together from one tag.
18
+
19
+ 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
20
+ parses lines faster.
21
+
22
+ ## Use
23
+
24
+ ```python
25
+ import atlasio
26
+
27
+ with atlasio.open_atlas("atlas.jsonl.gz") as atlas:
28
+ print(atlas.description, atlas.date, atlas.format_version)
29
+ print(atlas.params) # the atlas parameters (line 3)
30
+ for m in atlas:
31
+ m.name, m.weight, m.data
32
+ m.districting # {("WAKE",): 3, ("MECKLENBURG", "052"): 13, ...}
33
+ ```
34
+
35
+ District keys are tuples of names from the coarsest level down, as in AtlasIO.jl, whichever format version the
36
+ file uses. `m.raw_districting()` gives the same districting with v1-style string keys
37
+ (`'["MECKLENBURG", "052"]'`), for code written for the original `PythonReader/AtlasIO.py`.
38
+
39
+ Invalid files, a `formatVersion` this version does not know, and maps that break the format's rules raise
40
+ `atlasio.AtlasFormatError` (a `ValueError`).
41
+
42
+ The full API is in [function_calls.md](https://github.com/jonmjonm/AtlasIO.jl/blob/main/function_calls.md).
43
+
44
+ ## Write
45
+
46
+ ```python
47
+ with atlasio.new_atlas("out.jsonl.gz", description="my ensemble", params={"districts": 14}) as out:
48
+ out.add_map("map1", {("WAKE",): 3, ("MECKLENBURG", "052"): 13}, weight=1, data={"score": 0.5})
49
+ out.add_map(m) # or a Map, e.g. one read from another atlas
50
+ ```
51
+
52
+ `new_atlas(dest, description="", params={}, *, date=now, atlas_param_type, map_param_type, weight_type="Int64",
53
+ format_version=1, like=None)`. The compression is chosen by the extension; `dest` can also be an open file
54
+ object. `format_version=2` writes v2 (v1 is the default, as in AtlasIO.jl). `like=atlas` copies an open atlas's
55
+ header and parameters, for writing a modified copy; explicit arguments override it.
56
+
57
+ District keys are tuples of names and districts integers. Map data can be anything JSON can hold; numpy numbers
58
+ and arrays are converted. NaN and infinity are refused, since JSON has neither. A map that cannot be written
59
+ raises before any of it is written, so the file keeps every map written so far. In v2, a region both whole and
60
+ split (one key a prefix of another) raises `atlasio.AtlasFormatError`.
61
+
62
+ The output is laid out exactly as AtlasIO.jl writes it: the same banner, header and field order, and
63
+ byte-identical v2 assignments; only floats may be spelled differently (`1e-07` for Julia's `1.0e-7`).
64
+
65
+ ## Convert between format versions
66
+
67
+ ```
68
+ python -m atlasio convert atlas.jsonl.gz atlas_v2.jsonl.gz --to 2 # or: atlasio convert ...
69
+ ```
70
+
71
+ or `atlasio.convert("atlas.jsonl.gz", "atlas_v2.jsonl.gz", to=2)`. Only the header's `formatVersion` and each
72
+ map's assignment are rewritten; everything else is copied byte for byte, and converting back gives the same
73
+ districting for every map. A districting v2 cannot hold (a region both whole and split) stops the conversion
74
+ with an error naming the line and map. The output is byte-identical to AtlasIO.jl's `convertAtlas`.
75
+
76
+ ## Tests
77
+
78
+ From the repository root: `pip install ./python pytest && python -m pytest python/tests`.
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "AtlasIO"
7
+ dynamic = ["version"] # from atlasio.__version__ (src/atlasio/__init__.py), kept equal to AtlasIO.jl's version
8
+ description = "Read and write Atlas files (ensembles of redistricting maps), format versions 1 and 2, and convert between them"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"] # a copy of the repository's LICENSE (CI checks they match)
13
+ authors = [
14
+ { name = "Jonathan Mattingly", email = "jonathan.mattingly@duke.edu" },
15
+ { name = "Gregory Herschlag", email = "Gregory.Herschlag@duke.edu" },
16
+ ]
17
+ keywords = ["redistricting", "gerrymandering", "districting", "ensemble", "atlas"]
18
+ dependencies = []
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Science/Research",
22
+ "Topic :: Scientific/Engineering",
23
+ "Programming Language :: Python :: 3",
24
+ "Operating System :: OS Independent",
25
+ ]
26
+
27
+ [project.scripts]
28
+ atlasio = "atlasio.__main__:main"
29
+
30
+ [project.optional-dependencies]
31
+ fast = ["orjson"]
32
+ test = ["pytest"]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/jonmjonm/AtlasIO.jl"
36
+ Format = "https://github.com/jonmjonm/AtlasIO.jl/blob/main/atlas_format.md"
37
+ Changelog = "https://github.com/jonmjonm/AtlasIO.jl/blob/main/CHANGELOG.md"
38
+
39
+ [tool.setuptools.dynamic]
40
+ version = { attr = "atlasio.__version__" }
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/AtlasIO.egg-info/PKG-INFO
5
+ src/AtlasIO.egg-info/SOURCES.txt
6
+ src/AtlasIO.egg-info/dependency_links.txt
7
+ src/AtlasIO.egg-info/entry_points.txt
8
+ src/AtlasIO.egg-info/requires.txt
9
+ src/AtlasIO.egg-info/top_level.txt
10
+ src/atlasio/__init__.py
11
+ src/atlasio/__main__.py
12
+ src/atlasio/_convert.py
13
+ src/atlasio/_write.py
14
+ tests/test_atlasio.py
15
+ tests/test_convert.py
16
+ tests/test_release.py
17
+ tests/test_write.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ atlasio = atlasio.__main__:main
@@ -0,0 +1,6 @@
1
+
2
+ [fast]
3
+ orjson
4
+
5
+ [test]
6
+ pytest
@@ -0,0 +1 @@
1
+ atlasio
@@ -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