heatmap_cli 0.29.2__tar.gz → 0.29.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.
- {heatmap_cli-0.29.2/src/heatmap_cli.egg-info → heatmap_cli-0.29.4}/PKG-INFO +1 -1
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/pyproject.toml +1 -1
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli/__init__.py +21 -102
- heatmap_cli-0.29.4/src/heatmap_cli/actions.py +92 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli/cli.py +7 -22
- heatmap_cli-0.29.4/src/heatmap_cli/config.py +159 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli/heatmap.py +164 -132
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4/src/heatmap_cli.egg-info}/PKG-INFO +1 -1
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli.egg-info/SOURCES.txt +2 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_direct.py +24 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_errors.py +45 -1
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_style_option.py +22 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_iso_53_week_year.py +1 -1
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/LICENSE.md +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/README.md +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/setup.cfg +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli/__main__.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli/py.typed +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli.egg-info/dependency_links.txt +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli.egg-info/entry_points.txt +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli.egg-info/requires.txt +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/src/heatmap_cli.egg-info/top_level.txt +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_agg_backend.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_animate_by_week.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_animate_future_day.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_animate_no_frames.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_animate_open.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_annotate_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_annotation_truncation.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_cbar_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_cmap_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_cmax_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_cmin_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_configure_cbar.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_debug_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_demo_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_end_date_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_env_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_open.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_utils.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_heatmap_wrapper.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_help_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_main.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_no_annotate.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_open_heatmap.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_output_dir_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_purge_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_quiet_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_refresh_output_dir.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_setup_logging.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_start_date_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_supported_formats.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_title_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_version_flag.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_week_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_year_option.py +0 -0
- {heatmap_cli-0.29.2 → heatmap_cli-0.29.4}/tests/test_yes_flag.py +0 -0
|
@@ -28,7 +28,7 @@ classifiers = [
|
|
|
28
28
|
"Programming Language :: Python",
|
|
29
29
|
"Topic :: Scientific/Engineering :: Visualization",
|
|
30
30
|
]
|
|
31
|
-
version = "0.29.
|
|
31
|
+
version = "0.29.4"
|
|
32
32
|
keywords = ["heatmap", "cli", "visualization", "calendar", "data-viz"]
|
|
33
33
|
dependencies = [
|
|
34
34
|
"matplotlib",
|
|
@@ -19,54 +19,35 @@ from __future__ import annotations
|
|
|
19
19
|
|
|
20
20
|
import argparse
|
|
21
21
|
import logging
|
|
22
|
-
import platform
|
|
23
22
|
import random
|
|
24
|
-
import sys
|
|
25
|
-
from importlib import metadata
|
|
26
23
|
from pathlib import Path
|
|
27
|
-
from typing import Any, cast
|
|
28
24
|
|
|
29
|
-
import matplotlib as mpl
|
|
30
25
|
import pandas as pd
|
|
31
|
-
import seaborn as sns
|
|
32
26
|
|
|
27
|
+
from heatmap_cli.actions import DemoAction, EnvironmentAction
|
|
28
|
+
from heatmap_cli.config import (
|
|
29
|
+
CMAPS,
|
|
30
|
+
DEFAULT_DEMO_SEED,
|
|
31
|
+
DEMO_MAX_COUNT,
|
|
32
|
+
DEMO_SAMPLE_FILENAME,
|
|
33
|
+
FALLBACK_VERSION,
|
|
34
|
+
__version__,
|
|
35
|
+
_resolve_version,
|
|
36
|
+
)
|
|
33
37
|
from heatmap_cli.heatmap import _get_output_dir
|
|
34
38
|
from heatmap_cli.heatmap import run as generate_heatmaps
|
|
35
39
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
""
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"""
|
|
48
|
-
try:
|
|
49
|
-
return metadata.version("heatmap_cli")
|
|
50
|
-
except metadata.PackageNotFoundError:
|
|
51
|
-
return FALLBACK_VERSION
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
__version__ = _resolve_version()
|
|
55
|
-
|
|
56
|
-
# Max value for demo heatmap count
|
|
57
|
-
DEMO_MAX_COUNT = 12000
|
|
58
|
-
|
|
59
|
-
# Fixed default seed so --demo output is deterministic for docs and tests.
|
|
60
|
-
DEFAULT_DEMO_SEED = 42
|
|
61
|
-
|
|
62
|
-
# The demo sample CSV uses a dedicated, unlikely-to-collide name so --demo
|
|
63
|
-
# does not silently overwrite a user's file in the output directory.
|
|
64
|
-
DEMO_SAMPLE_FILENAME = "heatmap_demo_sample.csv"
|
|
65
|
-
|
|
66
|
-
# Sort colormaps in a case-insensitive manner.
|
|
67
|
-
# The colormap registry is read from matplotlib directly, not pyplot, so that
|
|
68
|
-
# importing the package never pulls in the pyplot backend machinery.
|
|
69
|
-
CMAPS = sorted(mpl.colormaps, key=str.casefold)
|
|
40
|
+
__all__ = [
|
|
41
|
+
"CMAPS",
|
|
42
|
+
"DEFAULT_DEMO_SEED",
|
|
43
|
+
"DEMO_MAX_COUNT",
|
|
44
|
+
"DEMO_SAMPLE_FILENAME",
|
|
45
|
+
"FALLBACK_VERSION",
|
|
46
|
+
"DemoAction",
|
|
47
|
+
"EnvironmentAction",
|
|
48
|
+
"__version__",
|
|
49
|
+
"_resolve_version",
|
|
50
|
+
]
|
|
70
51
|
|
|
71
52
|
logger = logging.getLogger(__name__)
|
|
72
53
|
|
|
@@ -118,33 +99,6 @@ def setup_logging(config: argparse.Namespace) -> None:
|
|
|
118
99
|
)
|
|
119
100
|
|
|
120
101
|
|
|
121
|
-
class DemoAction(argparse.Action):
|
|
122
|
-
"""Mark the demo flag and its required namespace values."""
|
|
123
|
-
|
|
124
|
-
def __init__(self, *nargs: object, **kwargs: object) -> None:
|
|
125
|
-
"""Overwrite class method."""
|
|
126
|
-
kwargs.update({"nargs": "?"})
|
|
127
|
-
super().__init__(*cast("Any", nargs), **cast("Any", kwargs))
|
|
128
|
-
|
|
129
|
-
def __call__(
|
|
130
|
-
self,
|
|
131
|
-
_parser: argparse.ArgumentParser,
|
|
132
|
-
namespace: argparse.Namespace,
|
|
133
|
-
values: object,
|
|
134
|
-
_option_string: str | None = None,
|
|
135
|
-
) -> None:
|
|
136
|
-
"""Record how many demo heatmaps to generate.
|
|
137
|
-
|
|
138
|
-
Only ``namespace.demo`` is set here. The demo flow's year, week,
|
|
139
|
-
colourbar and colormap defaults are applied once parsing has
|
|
140
|
-
finished (see `heatmap_cli.cli._apply_demo_overrides`), so that the
|
|
141
|
-
position of ``--demo`` on the command line cannot change the
|
|
142
|
-
outcome.
|
|
143
|
-
"""
|
|
144
|
-
demo_count = min(cast("int", values), len(CMAPS))
|
|
145
|
-
namespace.demo = max(demo_count, 1)
|
|
146
|
-
|
|
147
|
-
|
|
148
102
|
def generate_demo(config: argparse.Namespace) -> None:
|
|
149
103
|
"""Generate demo heatmaps with deterministic random state.
|
|
150
104
|
|
|
@@ -190,38 +144,3 @@ def _generate_sample_csv(config: argparse.Namespace) -> Path:
|
|
|
190
144
|
df_dates.to_csv(csv_filename, sep=",", index=False, header=False)
|
|
191
145
|
logger.debug("Generate sample CSV file: %s", csv_filename)
|
|
192
146
|
return csv_filename
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
class EnvironmentAction(argparse.Action):
|
|
196
|
-
"""Show environment details action."""
|
|
197
|
-
|
|
198
|
-
def __init__(self, *nargs: object, **kwargs: object) -> None:
|
|
199
|
-
"""Overwrite class method."""
|
|
200
|
-
kwargs["nargs"] = 0
|
|
201
|
-
super().__init__(*cast("Any", nargs), **cast("Any", kwargs))
|
|
202
|
-
|
|
203
|
-
def __call__(
|
|
204
|
-
self,
|
|
205
|
-
parser: argparse.ArgumentParser,
|
|
206
|
-
_namespace: argparse.Namespace,
|
|
207
|
-
_values: object,
|
|
208
|
-
_option_string: str | None = None,
|
|
209
|
-
) -> None:
|
|
210
|
-
"""Overwrite class method."""
|
|
211
|
-
sys_version = sys.version.replace("\n", "")
|
|
212
|
-
dependency_lines = "\n".join(
|
|
213
|
-
f"{name}: {version}"
|
|
214
|
-
for name, version in (
|
|
215
|
-
("matplotlib", mpl.__version__),
|
|
216
|
-
("pandas", pd.__version__),
|
|
217
|
-
("pillow", metadata.version("pillow")),
|
|
218
|
-
("seaborn", sns.__version__),
|
|
219
|
-
)
|
|
220
|
-
)
|
|
221
|
-
env = (
|
|
222
|
-
f"heatmap: {__version__}\n"
|
|
223
|
-
f"python: {sys_version}\n"
|
|
224
|
-
f"platform: {platform.platform()}\n"
|
|
225
|
-
f"{dependency_lines}\n"
|
|
226
|
-
)
|
|
227
|
-
parser.exit(message=env)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Copyright (C) 2023,2024,2025,2026 Kian-Meng Ang
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify it under
|
|
4
|
+
# the terms of the GNU Affero General Public License as published by the Free
|
|
5
|
+
# Software Foundation, either version 3 of the License, or (at your option) any
|
|
6
|
+
# later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
9
|
+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
10
|
+
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
11
|
+
# details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Custom argparse actions for the heatmap CLI."""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import platform
|
|
22
|
+
import sys
|
|
23
|
+
from importlib import metadata
|
|
24
|
+
from typing import Any, cast
|
|
25
|
+
|
|
26
|
+
import matplotlib as mpl
|
|
27
|
+
import pandas as pd
|
|
28
|
+
import seaborn as sns
|
|
29
|
+
|
|
30
|
+
from heatmap_cli.config import CMAPS, __version__
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class DemoAction(argparse.Action):
|
|
34
|
+
"""Mark the demo flag and its required namespace values."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, *nargs: object, **kwargs: object) -> None:
|
|
37
|
+
"""Overwrite class method."""
|
|
38
|
+
kwargs.update({"nargs": "?"})
|
|
39
|
+
super().__init__(*cast("Any", nargs), **cast("Any", kwargs))
|
|
40
|
+
|
|
41
|
+
def __call__(
|
|
42
|
+
self,
|
|
43
|
+
_parser: argparse.ArgumentParser,
|
|
44
|
+
namespace: argparse.Namespace,
|
|
45
|
+
values: object,
|
|
46
|
+
_option_string: str | None = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Record how many demo heatmaps to generate.
|
|
49
|
+
|
|
50
|
+
Only ``namespace.demo`` is set here. The demo flow's year, week,
|
|
51
|
+
colourbar and colormap defaults are applied once parsing has
|
|
52
|
+
finished (see `heatmap_cli.cli._apply_demo_overrides`), so that the
|
|
53
|
+
position of ``--demo`` on the command line cannot change the
|
|
54
|
+
outcome.
|
|
55
|
+
"""
|
|
56
|
+
demo_count = min(cast("int", values), len(CMAPS))
|
|
57
|
+
namespace.demo = max(demo_count, 1)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class EnvironmentAction(argparse.Action):
|
|
61
|
+
"""Show environment details action."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, *nargs: object, **kwargs: object) -> None:
|
|
64
|
+
"""Overwrite class method."""
|
|
65
|
+
kwargs["nargs"] = 0
|
|
66
|
+
super().__init__(*cast("Any", nargs), **cast("Any", kwargs))
|
|
67
|
+
|
|
68
|
+
def __call__(
|
|
69
|
+
self,
|
|
70
|
+
parser: argparse.ArgumentParser,
|
|
71
|
+
_namespace: argparse.Namespace,
|
|
72
|
+
_values: object,
|
|
73
|
+
_option_string: str | None = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Overwrite class method."""
|
|
76
|
+
sys_version = sys.version.replace("\n", "")
|
|
77
|
+
dependency_lines = "\n".join(
|
|
78
|
+
f"{name}: {version}"
|
|
79
|
+
for name, version in (
|
|
80
|
+
("matplotlib", mpl.__version__),
|
|
81
|
+
("pandas", pd.__version__),
|
|
82
|
+
("pillow", metadata.version("pillow")),
|
|
83
|
+
("seaborn", sns.__version__),
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
env = (
|
|
87
|
+
f"heatmap: {__version__}\n"
|
|
88
|
+
f"python: {sys_version}\n"
|
|
89
|
+
f"platform: {platform.platform()}\n"
|
|
90
|
+
f"{dependency_lines}\n"
|
|
91
|
+
)
|
|
92
|
+
parser.exit(message=env)
|
|
@@ -34,13 +34,15 @@ if TYPE_CHECKING:
|
|
|
34
34
|
|
|
35
35
|
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
36
36
|
|
|
37
|
-
from heatmap_cli import
|
|
37
|
+
from heatmap_cli import generate_demo, setup_logging
|
|
38
|
+
from heatmap_cli.actions import DemoAction, EnvironmentAction
|
|
39
|
+
from heatmap_cli.config import (
|
|
40
|
+
CMAP_ITEMS_PER_ROW,
|
|
38
41
|
CMAPS,
|
|
39
|
-
|
|
40
|
-
|
|
42
|
+
DEFAULT_CMAP,
|
|
43
|
+
DEMO_IGNORED_OPTIONS,
|
|
44
|
+
MAX_ISO_WEEK,
|
|
41
45
|
__version__,
|
|
42
|
-
generate_demo,
|
|
43
|
-
setup_logging,
|
|
44
46
|
)
|
|
45
47
|
from heatmap_cli.heatmap import (
|
|
46
48
|
_sanitize_string_for_filename,
|
|
@@ -75,23 +77,6 @@ IMAGE_FORMATS = _get_supported_formats()
|
|
|
75
77
|
|
|
76
78
|
logger = logging.getLogger(__name__)
|
|
77
79
|
|
|
78
|
-
DEFAULT_CMAP = "RdYlGn_r"
|
|
79
|
-
CMAP_ITEMS_PER_ROW = 6
|
|
80
|
-
MAX_ISO_WEEK = 53
|
|
81
|
-
|
|
82
|
-
# Options that --demo overrides. --demo synthesises its own sample data for
|
|
83
|
-
# the current ISO year, so the options that select or restyle *that* data have
|
|
84
|
-
# nothing left to act on. -b/--cbar is absent on purpose: it is a store_true
|
|
85
|
-
# already defaulted to False, and --demo forces it to True, which is exactly
|
|
86
|
-
# what -b asks for, so there is nothing to report.
|
|
87
|
-
DEMO_IGNORED_OPTIONS = (
|
|
88
|
-
("-y/--year", "year"),
|
|
89
|
-
("-w/--week", "week"),
|
|
90
|
-
("-s/--start-date", "start_date"),
|
|
91
|
-
("-e/--end-date", "end_date"),
|
|
92
|
-
("-c/--cmap", "cmap"),
|
|
93
|
-
)
|
|
94
|
-
|
|
95
80
|
|
|
96
81
|
def _valid_date(s: str) -> datetime.date:
|
|
97
82
|
"""Validate date format.
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# Copyright (C) 2023,2024,2025,2026 Kian-Meng Ang
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify it under
|
|
4
|
+
# the terms of the GNU Affero General Public License as published by the Free
|
|
5
|
+
# Software Foundation, either version 3 of the License, or (at your option) any
|
|
6
|
+
# later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
9
|
+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
10
|
+
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
11
|
+
# details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
|
|
16
|
+
"""Shared constants and distribution metadata for the heatmap CLI.
|
|
17
|
+
|
|
18
|
+
Keeping figure, colourbar, annotation, filename and CLI defaults in one module
|
|
19
|
+
makes them easy to find and change without hunting through the plotting and
|
|
20
|
+
argument-parsing code.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from importlib import metadata
|
|
26
|
+
|
|
27
|
+
import matplotlib as mpl
|
|
28
|
+
|
|
29
|
+
# Reported when the distribution metadata is unavailable, so that a source
|
|
30
|
+
# checkout which was never installed still runs instead of failing to import.
|
|
31
|
+
FALLBACK_VERSION = "0.0.0+unknown"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_version() -> str:
|
|
35
|
+
"""Return the version from the installed distribution metadata.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
str: The installed version, or ``FALLBACK_VERSION`` when the
|
|
39
|
+
package is not installed.
|
|
40
|
+
"""
|
|
41
|
+
try:
|
|
42
|
+
return metadata.version("heatmap_cli")
|
|
43
|
+
except metadata.PackageNotFoundError:
|
|
44
|
+
return FALLBACK_VERSION
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
__version__ = _resolve_version()
|
|
48
|
+
|
|
49
|
+
# Sort colormaps in a case-insensitive manner.
|
|
50
|
+
# The colormap registry is read from matplotlib directly, not pyplot, so that
|
|
51
|
+
# importing the package never pulls in the pyplot backend machinery.
|
|
52
|
+
CMAPS = sorted(mpl.colormaps, key=str.casefold)
|
|
53
|
+
|
|
54
|
+
# Demo settings
|
|
55
|
+
DEMO_MAX_COUNT = 12000
|
|
56
|
+
DEFAULT_DEMO_SEED = 42
|
|
57
|
+
DEMO_SAMPLE_FILENAME = "heatmap_demo_sample.csv"
|
|
58
|
+
|
|
59
|
+
# CLI defaults
|
|
60
|
+
DEFAULT_CMAP = "RdYlGn_r"
|
|
61
|
+
CMAP_ITEMS_PER_ROW = 6
|
|
62
|
+
MAX_ISO_WEEK = 53
|
|
63
|
+
|
|
64
|
+
# Options that --demo overrides. --demo synthesises its own sample data for
|
|
65
|
+
# the current ISO year, so the options that select or restyle *that* data have
|
|
66
|
+
# nothing left to act on. -b/--cbar is absent on purpose: it is a store_true
|
|
67
|
+
# already defaulted to False, and --demo forces it to True, which is exactly
|
|
68
|
+
# what -b asks for, so there is nothing to report.
|
|
69
|
+
DEMO_IGNORED_OPTIONS = (
|
|
70
|
+
("-y/--year", "year"),
|
|
71
|
+
("-w/--week", "week"),
|
|
72
|
+
("-s/--start-date", "start_date"),
|
|
73
|
+
("-e/--end-date", "end_date"),
|
|
74
|
+
("-c/--cmap", "cmap"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Define constants for figure and image settings
|
|
78
|
+
DEFAULT_FIGURE_SIZE = (8, 5)
|
|
79
|
+
DEFAULT_DPI = 76
|
|
80
|
+
|
|
81
|
+
# Define constants for GIF animation settings
|
|
82
|
+
GIF_DURATION_MS = 1000
|
|
83
|
+
GIF_LOOP_COUNT = 0
|
|
84
|
+
|
|
85
|
+
# Define constants for font sizes
|
|
86
|
+
DEFAULT_TICK_LABEL_FONTSIZE = 9
|
|
87
|
+
ANNOTATION_FONTSIZE = 8
|
|
88
|
+
TITLE_FONTSIZE = 11
|
|
89
|
+
GRADE_LEGEND_FONTSIZE = 9
|
|
90
|
+
|
|
91
|
+
# Define constants for colorbar settings
|
|
92
|
+
COLORBAR_PAD = 0.10
|
|
93
|
+
COLORBAR_ASPECT = 60
|
|
94
|
+
|
|
95
|
+
# Define constant for filename sanitization
|
|
96
|
+
MAX_FILENAME_LENGTH = 100
|
|
97
|
+
|
|
98
|
+
WEEKS_IN_YEAR = 52
|
|
99
|
+
|
|
100
|
+
# Define constants for annotation thresholds
|
|
101
|
+
ANNOTATION_THRESHOLD = 100
|
|
102
|
+
|
|
103
|
+
# Letter grade scale for --heatmap-style grade: X (10k+), A (7.5k-10k),
|
|
104
|
+
# B (5k-7.5k), C (2.5k-5k), D (1k-2.5k), E (<1k), and a dot for a day
|
|
105
|
+
# without steps. Counts are in the truncated annotation units (hundreds
|
|
106
|
+
# of steps), so 100 is 10,000 steps.
|
|
107
|
+
GRADE_THRESHOLDS = (
|
|
108
|
+
(100, "X"),
|
|
109
|
+
(75, "A"),
|
|
110
|
+
(50, "B"),
|
|
111
|
+
(25, "C"),
|
|
112
|
+
(10, "D"),
|
|
113
|
+
)
|
|
114
|
+
GRADE_FALLBACK = "E"
|
|
115
|
+
GRADE_ZERO = "."
|
|
116
|
+
|
|
117
|
+
# Grade scale legend shown below a heatmap with graded annotations. Each
|
|
118
|
+
# entry is the grade letter, its step range label, and a representative
|
|
119
|
+
# count in the truncated annotation units, used to sample the heatmap
|
|
120
|
+
# color that the letter is drawn in.
|
|
121
|
+
GRADE_LEGEND_LABEL = "Legend:"
|
|
122
|
+
GRADE_LEGEND_ENTRIES = (
|
|
123
|
+
("X", "10k+", 110),
|
|
124
|
+
("A", "7.5-10k", 87),
|
|
125
|
+
("B", "5-7.5k", 62),
|
|
126
|
+
("C", "2.5-5k", 37),
|
|
127
|
+
("D", "1-2.5k", 17),
|
|
128
|
+
("E", "<1k", 5),
|
|
129
|
+
(GRADE_ZERO, "0", 0),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Vertical distance in points between the axes bottom and the top of the
|
|
133
|
+
# grade legend block.
|
|
134
|
+
GRADE_LEGEND_OFFSET = -18
|
|
135
|
+
|
|
136
|
+
# Vertical spacing in points between the week label and the grade legend
|
|
137
|
+
# below it.
|
|
138
|
+
WEEK_LEGEND_GAP = 4
|
|
139
|
+
|
|
140
|
+
# Vertical spacing in points between the grade legend row and the
|
|
141
|
+
# "Generated by" row below it.
|
|
142
|
+
LEGEND_GENERATED_GAP = 2
|
|
143
|
+
|
|
144
|
+
# Define constants for default title strings
|
|
145
|
+
DEFAULT_TITLE_PREFIX = "Year {config.year}: Total Daily Walking Steps"
|
|
146
|
+
DEFAULT_TITLE_WEEK_SUFFIX = " Through Week {config.week:02d}"
|
|
147
|
+
|
|
148
|
+
# Define constants for colorbar labels
|
|
149
|
+
COLORBAR_BASE_LABEL = (
|
|
150
|
+
"Generated by: pypi.org/project/heatmap_cli, colormap: {cmap}"
|
|
151
|
+
)
|
|
152
|
+
COLORBAR_ANNOTATION_SUFFIX = ", count: nearest hundred"
|
|
153
|
+
|
|
154
|
+
# Define constants for count truncation
|
|
155
|
+
TRUNCATE_DIVISOR = 100
|
|
156
|
+
|
|
157
|
+
# Define constants for week ranges
|
|
158
|
+
ALL_WEEKS_RANGE = range(1, 54)
|
|
159
|
+
ALL_WEEKDAYS_RANGE = range(1, 8)
|
|
@@ -20,14 +20,15 @@ from __future__ import annotations
|
|
|
20
20
|
import copy
|
|
21
21
|
import io
|
|
22
22
|
import logging
|
|
23
|
+
import math
|
|
23
24
|
import multiprocessing
|
|
24
25
|
import os
|
|
25
26
|
import re
|
|
26
27
|
import shutil
|
|
27
28
|
import webbrowser
|
|
28
|
-
from datetime import
|
|
29
|
+
from datetime import date, datetime, timedelta
|
|
29
30
|
from pathlib import Path
|
|
30
|
-
from typing import TYPE_CHECKING, Any, cast
|
|
31
|
+
from typing import TYPE_CHECKING, Any, Literal, cast, overload
|
|
31
32
|
|
|
32
33
|
if TYPE_CHECKING:
|
|
33
34
|
import argparse
|
|
@@ -45,89 +46,36 @@ from matplotlib.figure import Figure
|
|
|
45
46
|
from matplotlib.offsetbox import AnnotationBbox, HPacker, TextArea, VPacker
|
|
46
47
|
from PIL import Image
|
|
47
48
|
|
|
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
|
-
# of steps), so 100 is 10,000 steps.
|
|
78
|
-
GRADE_THRESHOLDS = (
|
|
79
|
-
(100, "X"),
|
|
80
|
-
(75, "A"),
|
|
81
|
-
(50, "B"),
|
|
82
|
-
(25, "C"),
|
|
83
|
-
(10, "D"),
|
|
49
|
+
from heatmap_cli.config import (
|
|
50
|
+
ALL_WEEKDAYS_RANGE,
|
|
51
|
+
ALL_WEEKS_RANGE,
|
|
52
|
+
ANNOTATION_FONTSIZE,
|
|
53
|
+
ANNOTATION_THRESHOLD,
|
|
54
|
+
COLORBAR_ANNOTATION_SUFFIX,
|
|
55
|
+
COLORBAR_ASPECT,
|
|
56
|
+
COLORBAR_BASE_LABEL,
|
|
57
|
+
COLORBAR_PAD,
|
|
58
|
+
DEFAULT_DPI,
|
|
59
|
+
DEFAULT_FIGURE_SIZE,
|
|
60
|
+
DEFAULT_TICK_LABEL_FONTSIZE,
|
|
61
|
+
DEFAULT_TITLE_PREFIX,
|
|
62
|
+
DEFAULT_TITLE_WEEK_SUFFIX,
|
|
63
|
+
GIF_DURATION_MS,
|
|
64
|
+
GIF_LOOP_COUNT,
|
|
65
|
+
GRADE_FALLBACK,
|
|
66
|
+
GRADE_LEGEND_ENTRIES,
|
|
67
|
+
GRADE_LEGEND_FONTSIZE,
|
|
68
|
+
GRADE_LEGEND_LABEL,
|
|
69
|
+
GRADE_LEGEND_OFFSET,
|
|
70
|
+
GRADE_THRESHOLDS,
|
|
71
|
+
GRADE_ZERO,
|
|
72
|
+
LEGEND_GENERATED_GAP,
|
|
73
|
+
MAX_FILENAME_LENGTH,
|
|
74
|
+
TITLE_FONTSIZE,
|
|
75
|
+
TRUNCATE_DIVISOR,
|
|
76
|
+
WEEK_LEGEND_GAP,
|
|
77
|
+
WEEKS_IN_YEAR,
|
|
84
78
|
)
|
|
85
|
-
GRADE_FALLBACK = "E"
|
|
86
|
-
GRADE_ZERO = "."
|
|
87
|
-
|
|
88
|
-
# Grade scale legend shown below a heatmap with graded annotations. Each
|
|
89
|
-
# entry is the grade letter, its step range label, and a representative
|
|
90
|
-
# count in the truncated annotation units, used to sample the heatmap
|
|
91
|
-
# color that the letter is drawn in.
|
|
92
|
-
GRADE_LEGEND_LABEL = "Legend:"
|
|
93
|
-
GRADE_LEGEND_ENTRIES = (
|
|
94
|
-
("X", "10k+", 110),
|
|
95
|
-
("A", "7.5-10k", 87),
|
|
96
|
-
("B", "5-7.5k", 62),
|
|
97
|
-
("C", "2.5-5k", 37),
|
|
98
|
-
("D", "1-2.5k", 17),
|
|
99
|
-
("E", "<1k", 5),
|
|
100
|
-
(GRADE_ZERO, "0", 0),
|
|
101
|
-
)
|
|
102
|
-
|
|
103
|
-
# Vertical distance in points between the axes bottom and the top of the
|
|
104
|
-
# grade legend block.
|
|
105
|
-
GRADE_LEGEND_OFFSET = -18
|
|
106
|
-
|
|
107
|
-
# Vertical spacing in points between the week label and the grade legend
|
|
108
|
-
# below it.
|
|
109
|
-
WEEK_LEGEND_GAP = 4
|
|
110
|
-
|
|
111
|
-
# Vertical spacing in points between the grade legend row and the
|
|
112
|
-
# "Generated by" row below it.
|
|
113
|
-
LEGEND_GENERATED_GAP = 2
|
|
114
|
-
|
|
115
|
-
# Define constants for default title strings
|
|
116
|
-
DEFAULT_TITLE_PREFIX = "Year {config.year}: Total Daily Walking Steps"
|
|
117
|
-
DEFAULT_TITLE_WEEK_SUFFIX = " Through Week {config.week:02d}"
|
|
118
|
-
|
|
119
|
-
# Define constants for colorbar labels
|
|
120
|
-
COLORBAR_BASE_LABEL = (
|
|
121
|
-
"Generated by: pypi.org/project/heatmap_cli, colormap: {cmap}"
|
|
122
|
-
)
|
|
123
|
-
COLORBAR_ANNOTATION_SUFFIX = ", count: nearest hundred"
|
|
124
|
-
|
|
125
|
-
# Define constants for count truncation
|
|
126
|
-
TRUNCATE_DIVISOR = 100
|
|
127
|
-
|
|
128
|
-
# Define constants for week ranges
|
|
129
|
-
ALL_WEEKS_RANGE = range(1, 54)
|
|
130
|
-
ALL_WEEKDAYS_RANGE = range(1, 8)
|
|
131
79
|
|
|
132
80
|
logger = logging.getLogger(__name__)
|
|
133
81
|
|
|
@@ -205,11 +153,10 @@ def _week_start_date(year: int, week: int) -> date:
|
|
|
205
153
|
Returns:
|
|
206
154
|
date: The date of the Monday that starts the week.
|
|
207
155
|
"""
|
|
208
|
-
return (
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
)
|
|
156
|
+
return datetime.strptime( # noqa: DTZ007
|
|
157
|
+
f"{year}-W{week}-1",
|
|
158
|
+
"%G-W%V-%u",
|
|
159
|
+
).date()
|
|
213
160
|
|
|
214
161
|
|
|
215
162
|
def _generate_animated_heatmap(
|
|
@@ -270,7 +217,7 @@ def _generate_animated_heatmap(
|
|
|
270
217
|
return_image=True,
|
|
271
218
|
)
|
|
272
219
|
if frame:
|
|
273
|
-
frames.append(
|
|
220
|
+
frames.append(frame)
|
|
274
221
|
|
|
275
222
|
if not frames:
|
|
276
223
|
logger.warning("no frames generated to create GIF animation.")
|
|
@@ -342,15 +289,12 @@ def _generate_static_heatmaps(
|
|
|
342
289
|
# still returning the generated file so opening works as before.
|
|
343
290
|
seq, cmap = args[0][:2] # (seq, cmap, ...)
|
|
344
291
|
generated_files = [
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
pivoted_dataframe,
|
|
352
|
-
return_image=False,
|
|
353
|
-
),
|
|
292
|
+
_generate_heatmap(
|
|
293
|
+
seq,
|
|
294
|
+
cmap,
|
|
295
|
+
config,
|
|
296
|
+
pivoted_dataframe,
|
|
297
|
+
return_image=False,
|
|
354
298
|
)
|
|
355
299
|
]
|
|
356
300
|
else:
|
|
@@ -379,18 +323,69 @@ def _generate_heatmap_wrapper(
|
|
|
379
323
|
Workers always save to disk (``return_image=False``), so the result is a
|
|
380
324
|
file Path, never an in-memory image.
|
|
381
325
|
"""
|
|
382
|
-
return
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
dataframe,
|
|
389
|
-
return_image=False,
|
|
390
|
-
),
|
|
326
|
+
return _generate_heatmap(
|
|
327
|
+
seq,
|
|
328
|
+
cmap,
|
|
329
|
+
config,
|
|
330
|
+
dataframe,
|
|
331
|
+
return_image=False,
|
|
391
332
|
)
|
|
392
333
|
|
|
393
334
|
|
|
335
|
+
def _find_invalid_count_line(filename: str | Path) -> int | None:
|
|
336
|
+
"""Find the line number of the first invalid count in a CSV file.
|
|
337
|
+
|
|
338
|
+
Called only after pandas has rejected the count column. It re-reads the
|
|
339
|
+
counts as text, leaving accepted input unchanged, so the parser's generic
|
|
340
|
+
error can be reported with the offending row's line number.
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
filename (str | Path): The CSV file that failed to parse.
|
|
344
|
+
|
|
345
|
+
Returns:
|
|
346
|
+
int | None: The 1-based line number of the first invalid count, or
|
|
347
|
+
None if the problem could not be located.
|
|
348
|
+
"""
|
|
349
|
+
path = Path(filename)
|
|
350
|
+
try:
|
|
351
|
+
counts = pd.read_csv(
|
|
352
|
+
path,
|
|
353
|
+
header=None,
|
|
354
|
+
names=["date", "count"],
|
|
355
|
+
dtype="string",
|
|
356
|
+
)["count"]
|
|
357
|
+
except ValueError:
|
|
358
|
+
return None
|
|
359
|
+
|
|
360
|
+
if counts.empty:
|
|
361
|
+
return None
|
|
362
|
+
|
|
363
|
+
numeric = pd.to_numeric(counts, errors="coerce").astype("float64")
|
|
364
|
+
invalid = ~numeric.map(
|
|
365
|
+
lambda value: math.isfinite(value) and float(value).is_integer(),
|
|
366
|
+
)
|
|
367
|
+
first_invalid = next(
|
|
368
|
+
(index for index, is_invalid in enumerate(invalid) if is_invalid),
|
|
369
|
+
None,
|
|
370
|
+
)
|
|
371
|
+
if first_invalid is None:
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
try:
|
|
375
|
+
with path.open(encoding="utf-8") as handle:
|
|
376
|
+
# pandas skips blank lines, so map the row position onto the
|
|
377
|
+
# physical line number of the corresponding non-blank line.
|
|
378
|
+
data_lines = [
|
|
379
|
+
line_number
|
|
380
|
+
for line_number, line in enumerate(handle, 1)
|
|
381
|
+
if line.strip()
|
|
382
|
+
]
|
|
383
|
+
except OSError:
|
|
384
|
+
return None
|
|
385
|
+
|
|
386
|
+
return data_lines[first_invalid]
|
|
387
|
+
|
|
388
|
+
|
|
394
389
|
def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
|
|
395
390
|
"""Reads and performs initial preparation of the data from the CSV file.
|
|
396
391
|
|
|
@@ -421,9 +416,11 @@ def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
|
|
|
421
416
|
logger.error("Input file not found: %s", config.input_filename)
|
|
422
417
|
raise
|
|
423
418
|
except ValueError as error:
|
|
419
|
+
line = _find_invalid_count_line(config.input_filename)
|
|
420
|
+
location = f" (line {line})" if line is not None else ""
|
|
424
421
|
msg = (
|
|
425
422
|
"Invalid count values in input CSV: "
|
|
426
|
-
f"{config.input_filename}, expected an integer."
|
|
423
|
+
f"{config.input_filename}, expected an integer{location}."
|
|
427
424
|
)
|
|
428
425
|
raise ValueError(msg) from error
|
|
429
426
|
|
|
@@ -459,7 +456,7 @@ def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
|
|
|
459
456
|
msg = f"Duplicate dates found: {dup_dates_str}"
|
|
460
457
|
raise ValueError(msg)
|
|
461
458
|
|
|
462
|
-
dataframe["weekday"] = dataframe["date"].dt.
|
|
459
|
+
dataframe["weekday"] = dataframe["date"].dt.day_of_week + 1
|
|
463
460
|
dataframe["year"] = dataframe["date"].dt.isocalendar().year
|
|
464
461
|
dataframe["week"] = (
|
|
465
462
|
dataframe["date"].dt.isocalendar().week.astype(str).str.zfill(2)
|
|
@@ -526,7 +523,9 @@ def _filter_and_pivot_data(
|
|
|
526
523
|
logger.debug("end date: %s", end_date)
|
|
527
524
|
full_year_dates = pd.date_range(start=start_date, end=end_date, freq="D")
|
|
528
525
|
full_year_structure = pd.DataFrame({"date": full_year_dates})
|
|
529
|
-
full_year_structure["weekday"] =
|
|
526
|
+
full_year_structure["weekday"] = (
|
|
527
|
+
full_year_structure["date"].dt.day_of_week + 1
|
|
528
|
+
)
|
|
530
529
|
full_year_structure["week"] = (
|
|
531
530
|
full_year_structure["date"]
|
|
532
531
|
.dt.isocalendar()
|
|
@@ -621,6 +620,28 @@ def _setup_plot_artists(
|
|
|
621
620
|
return fig, axis
|
|
622
621
|
|
|
623
622
|
|
|
623
|
+
@overload
|
|
624
|
+
def _generate_heatmap(
|
|
625
|
+
seq: int,
|
|
626
|
+
cmap: str,
|
|
627
|
+
config: argparse.Namespace,
|
|
628
|
+
dataframe: pd.DataFrame,
|
|
629
|
+
*,
|
|
630
|
+
return_image: Literal[True],
|
|
631
|
+
) -> Image.Image: ...
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
@overload
|
|
635
|
+
def _generate_heatmap(
|
|
636
|
+
seq: int,
|
|
637
|
+
cmap: str,
|
|
638
|
+
config: argparse.Namespace,
|
|
639
|
+
dataframe: pd.DataFrame,
|
|
640
|
+
*,
|
|
641
|
+
return_image: Literal[False] = False,
|
|
642
|
+
) -> Path: ...
|
|
643
|
+
|
|
644
|
+
|
|
624
645
|
def _generate_heatmap(
|
|
625
646
|
seq: int,
|
|
626
647
|
cmap: str,
|
|
@@ -628,7 +649,7 @@ def _generate_heatmap(
|
|
|
628
649
|
dataframe: pd.DataFrame,
|
|
629
650
|
*,
|
|
630
651
|
return_image: bool = False,
|
|
631
|
-
) -> Image.Image | Path
|
|
652
|
+
) -> Image.Image | Path:
|
|
632
653
|
"""Generate a heatmap.
|
|
633
654
|
|
|
634
655
|
Args:
|
|
@@ -641,8 +662,8 @@ def _generate_heatmap(
|
|
|
641
662
|
saving to disk.
|
|
642
663
|
|
|
643
664
|
Returns:
|
|
644
|
-
|
|
645
|
-
|
|
665
|
+
Image.Image | Path: The PIL Image object if return_image is True,
|
|
666
|
+
otherwise the Path of the saved heatmap file.
|
|
646
667
|
"""
|
|
647
668
|
fig, axis = _setup_plot_artists(cmap, config, dataframe)
|
|
648
669
|
|
|
@@ -915,17 +936,24 @@ def _render_heatmap_image(fig: Figure) -> Image.Image:
|
|
|
915
936
|
Returns:
|
|
916
937
|
Image.Image: The rendered heatmap as a PIL Image object.
|
|
917
938
|
"""
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
939
|
+
try:
|
|
940
|
+
fig.tight_layout()
|
|
941
|
+
buffer = io.BytesIO()
|
|
942
|
+
fig.savefig(
|
|
943
|
+
buffer,
|
|
944
|
+
bbox_inches="tight",
|
|
945
|
+
transparent=False,
|
|
946
|
+
dpi=DEFAULT_DPI,
|
|
947
|
+
format="png",
|
|
948
|
+
)
|
|
949
|
+
buffer.seek(0)
|
|
950
|
+
return Image.open(buffer).copy()
|
|
951
|
+
finally:
|
|
952
|
+
# Figures use the object-oriented API, so pyplot never registers them
|
|
953
|
+
# and plt.close() would be a no-op. Clearing releases the axes,
|
|
954
|
+
# artists, and image data right away instead of waiting for the GC,
|
|
955
|
+
# which keeps memory flat across animation frames and colormaps.
|
|
956
|
+
fig.clear()
|
|
929
957
|
|
|
930
958
|
|
|
931
959
|
def _save_heatmap_figure(
|
|
@@ -952,13 +980,17 @@ def _save_heatmap_figure(
|
|
|
952
980
|
img_filename = output_dir / _generate_filename(config, seq, cmap, title)
|
|
953
981
|
img_filename.parent.mkdir(parents=True, exist_ok=True)
|
|
954
982
|
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
983
|
+
try:
|
|
984
|
+
fig.savefig(
|
|
985
|
+
img_filename,
|
|
986
|
+
bbox_inches="tight",
|
|
987
|
+
transparent=False,
|
|
988
|
+
dpi=DEFAULT_DPI,
|
|
989
|
+
format=config.format,
|
|
990
|
+
)
|
|
991
|
+
finally:
|
|
992
|
+
# See _render_heatmap_image: pyplot does not track these figures.
|
|
993
|
+
fig.clear()
|
|
962
994
|
return img_filename
|
|
963
995
|
|
|
964
996
|
|
|
@@ -22,6 +22,7 @@ from PIL import Image
|
|
|
22
22
|
from heatmap_cli.heatmap import (
|
|
23
23
|
_generate_heatmap,
|
|
24
24
|
_render_heatmap_image,
|
|
25
|
+
_save_heatmap_figure,
|
|
25
26
|
_setup_plot_artists,
|
|
26
27
|
)
|
|
27
28
|
|
|
@@ -70,3 +71,26 @@ def test_render_heatmap_image(tmpdir):
|
|
|
70
71
|
image = _render_heatmap_image(fig)
|
|
71
72
|
|
|
72
73
|
assert isinstance(image, Image.Image)
|
|
74
|
+
# The figure is released after rendering so long batch runs do not keep
|
|
75
|
+
# every rendered figure and its artists alive.
|
|
76
|
+
assert fig.axes == []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_save_heatmap_figure_releases_figure(tmpdir):
|
|
80
|
+
config = argparse.Namespace(
|
|
81
|
+
annotate=False,
|
|
82
|
+
cbar=False,
|
|
83
|
+
cmap_min=None,
|
|
84
|
+
cmap_max=None,
|
|
85
|
+
output_dir=str(tmpdir),
|
|
86
|
+
format="png",
|
|
87
|
+
heatmap_style="number",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
df = pd.DataFrame([[10, 20], [30, 40]], index=[1, 2], columns=["01", "02"])
|
|
91
|
+
|
|
92
|
+
fig, _axis = _setup_plot_artists("vlag", config, df)
|
|
93
|
+
img_filename = _save_heatmap_figure(fig, config, 1, "vlag", "Test Title")
|
|
94
|
+
|
|
95
|
+
assert img_filename.exists()
|
|
96
|
+
assert fig.axes == []
|
|
@@ -19,7 +19,11 @@ from unittest.mock import patch
|
|
|
19
19
|
|
|
20
20
|
import pytest
|
|
21
21
|
|
|
22
|
-
from heatmap_cli.heatmap import
|
|
22
|
+
from heatmap_cli.heatmap import (
|
|
23
|
+
_find_invalid_count_line,
|
|
24
|
+
_read_and_prepare_data,
|
|
25
|
+
_refresh_output_dir,
|
|
26
|
+
)
|
|
23
27
|
|
|
24
28
|
|
|
25
29
|
def test_file_not_found_error_direct(tmpdir):
|
|
@@ -112,6 +116,46 @@ def test_invalid_count_error_cli(cli_runner, tmpdir):
|
|
|
112
116
|
assert ret.returncode == 1
|
|
113
117
|
|
|
114
118
|
|
|
119
|
+
def test_invalid_count_error_reports_line_number(tmpdir):
|
|
120
|
+
"""The error points at the physical line, even across blank lines."""
|
|
121
|
+
csv_path = _write_csv(
|
|
122
|
+
tmpdir,
|
|
123
|
+
"bad_count.csv",
|
|
124
|
+
["2023-01-01,10", "2023-01-02,20", "", "2023-01-03,abc"],
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
config = argparse.Namespace(input_filename=str(csv_path), annotate=False)
|
|
128
|
+
with pytest.raises(ValueError, match=r"expected an integer \(line 4\)"):
|
|
129
|
+
_read_and_prepare_data(config)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_invalid_count_error_omits_line_when_unlocatable(tmpdir):
|
|
133
|
+
"""A CSV that cannot be re-read still gets the original error."""
|
|
134
|
+
csv_path = Path(tmpdir) / "unclosed.csv"
|
|
135
|
+
csv_path.write_text('2023-01-01,"10\n')
|
|
136
|
+
|
|
137
|
+
config = argparse.Namespace(input_filename=str(csv_path), annotate=False)
|
|
138
|
+
with pytest.raises(ValueError, match="expected an integer") as exc_info:
|
|
139
|
+
_read_and_prepare_data(config)
|
|
140
|
+
assert "(line" not in str(exc_info.value)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_find_invalid_count_line_returns_none_if_file_cannot_be_opened(tmpdir):
|
|
144
|
+
csv_path = _write_csv(tmpdir, "invalid.csv", ["2023-01-01,abc"])
|
|
145
|
+
|
|
146
|
+
with patch.object(Path, "open", side_effect=OSError("boom")):
|
|
147
|
+
assert _find_invalid_count_line(csv_path) is None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_find_invalid_count_line_returns_none_for_valid_or_empty_csv(tmpdir):
|
|
151
|
+
valid = _write_csv(tmpdir, "valid.csv", ["2023-01-01,10"])
|
|
152
|
+
empty = Path(tmpdir) / "empty.csv"
|
|
153
|
+
empty.write_text("")
|
|
154
|
+
|
|
155
|
+
assert _find_invalid_count_line(valid) is None
|
|
156
|
+
assert _find_invalid_count_line(empty) is None
|
|
157
|
+
|
|
158
|
+
|
|
115
159
|
def test_empty_csv_error_cli(cli_runner, tmpdir):
|
|
116
160
|
csv_path = Path(tmpdir) / "empty.csv"
|
|
117
161
|
csv_path.write_text("")
|
|
@@ -143,6 +143,28 @@ def test_heatmap_style_grade_ignores_colorbar(csv_file):
|
|
|
143
143
|
_assert_legend_rows(axis)
|
|
144
144
|
|
|
145
145
|
|
|
146
|
+
def test_heatmap_style_grade_without_xlabel(csv_file):
|
|
147
|
+
"""The grade legend omits the week row when the axis has no xlabel."""
|
|
148
|
+
csv = csv_file("sample.csv")
|
|
149
|
+
parser = build_parser()
|
|
150
|
+
parsed_args = parser.parse_args([str(csv), "--heatmap-style", "grade"])
|
|
151
|
+
config = _process_args(parser, parsed_args)
|
|
152
|
+
|
|
153
|
+
dataframe = pd.DataFrame(
|
|
154
|
+
GRADE_DATA,
|
|
155
|
+
index=[1, 2],
|
|
156
|
+
columns=["01", "02", "03", "04"],
|
|
157
|
+
)
|
|
158
|
+
dataframe.index.name = "weekday"
|
|
159
|
+
_fig, axis = _setup_plot_artists("vlag", config, dataframe)
|
|
160
|
+
|
|
161
|
+
areas = _legend_areas(axis)
|
|
162
|
+
texts = [area.get_text() for area in areas]
|
|
163
|
+
assert texts[0] == GRADE_LEGEND_LABEL
|
|
164
|
+
assert "".join(texts[:-1]) == _expected_legend_line()
|
|
165
|
+
assert texts[-1] == GENERATED_BY
|
|
166
|
+
|
|
167
|
+
|
|
146
168
|
def test_heatmap_style_number_keeps_colorbar_without_legend(csv_file):
|
|
147
169
|
"""The number style keeps the colorbar and draws no grade legend."""
|
|
148
170
|
csv = csv_file("sample.csv")
|
|
@@ -37,7 +37,7 @@ def _base_dataframe(rows: list[tuple[str, int]]) -> pd.DataFrame:
|
|
|
37
37
|
"""Build a prepared DataFrame as done by _read_and_prepare_data."""
|
|
38
38
|
df = pd.DataFrame(rows, columns=["date", "count"])
|
|
39
39
|
df["date"] = pd.to_datetime(df["date"])
|
|
40
|
-
df["weekday"] = df["date"].dt.
|
|
40
|
+
df["weekday"] = df["date"].dt.day_of_week + 1
|
|
41
41
|
df["year"] = df["date"].dt.isocalendar().year
|
|
42
42
|
df["week"] = df["date"].dt.isocalendar().week.astype(str).str.zfill(2)
|
|
43
43
|
return df
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|