pivograph 0.1.0__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.
- pivograph/__init__.py +37 -0
- pivograph/__main__.py +103 -0
- pivograph/_check.py +311 -0
- pivograph/_hints.py +74 -0
- pivograph/_project.py +164 -0
- pivograph/_report.py +94 -0
- pivograph/_rules.py +555 -0
- pivograph/_schema.py +543 -0
- pivograph/data/rules.json +829 -0
- pivograph/data/v1.json +3986 -0
- pivograph/data/v2.json +4400 -0
- pivograph/data/v3.json +4702 -0
- pivograph/py.typed +1 -0
- pivograph-0.1.0.dist-info/METADATA +153 -0
- pivograph-0.1.0.dist-info/RECORD +18 -0
- pivograph-0.1.0.dist-info/WHEEL +4 -0
- pivograph-0.1.0.dist-info/entry_points.txt +2 -0
- pivograph-0.1.0.dist-info/licenses/LICENSE +21 -0
pivograph/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Read, check and save PivoGraph project files (.pivograph)."""
|
|
2
|
+
|
|
3
|
+
from ._check import check, check_bytes, check_document, check_text, save
|
|
4
|
+
from ._project import Project, Table, load
|
|
5
|
+
from ._report import InvalidProjectError, Issue, Report
|
|
6
|
+
from ._rules import analyses_for, load_data, rules, variants_for
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
#: The file format version this package writes and checks in full.
|
|
11
|
+
SCHEMA_VERSION: int = rules()["schemaVersion"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def json_schema(version: int = SCHEMA_VERSION) -> dict:
|
|
15
|
+
"""The published JSON Schema of a file format version."""
|
|
16
|
+
schema: dict = load_data(f"v{version}.json")
|
|
17
|
+
return schema
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"InvalidProjectError",
|
|
22
|
+
"Issue",
|
|
23
|
+
"Project",
|
|
24
|
+
"Report",
|
|
25
|
+
"SCHEMA_VERSION",
|
|
26
|
+
"Table",
|
|
27
|
+
"analyses_for",
|
|
28
|
+
"check",
|
|
29
|
+
"check_bytes",
|
|
30
|
+
"check_document",
|
|
31
|
+
"check_text",
|
|
32
|
+
"json_schema",
|
|
33
|
+
"load",
|
|
34
|
+
"save",
|
|
35
|
+
"variants_for",
|
|
36
|
+
"__version__",
|
|
37
|
+
]
|
pivograph/__main__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Command line: ``python -m pivograph check figure.pivograph``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import List, Optional
|
|
9
|
+
|
|
10
|
+
from . import (
|
|
11
|
+
SCHEMA_VERSION,
|
|
12
|
+
InvalidProjectError,
|
|
13
|
+
__version__,
|
|
14
|
+
analyses_for,
|
|
15
|
+
check,
|
|
16
|
+
json_schema,
|
|
17
|
+
load,
|
|
18
|
+
rules,
|
|
19
|
+
variants_for,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
24
|
+
for stream in (sys.stdout, sys.stderr):
|
|
25
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
26
|
+
if reconfigure is not None:
|
|
27
|
+
reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
28
|
+
|
|
29
|
+
parser = argparse.ArgumentParser(
|
|
30
|
+
prog="pivograph", description="Read and check PivoGraph project files (.pivograph)."
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument("--version", action="version", version=f"pivograph {__version__}")
|
|
33
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
34
|
+
|
|
35
|
+
command = commands.add_parser("check", help="report every problem in a project file")
|
|
36
|
+
command.add_argument("file", nargs="+")
|
|
37
|
+
command.add_argument(
|
|
38
|
+
"--allow-warnings", action="store_true", help="exit with 0 when there are only warnings"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
command = commands.add_parser("tables", help="list the data tables of a project file")
|
|
42
|
+
command.add_argument("file")
|
|
43
|
+
|
|
44
|
+
command = commands.add_parser("csv", help="write one data table as CSV")
|
|
45
|
+
command.add_argument("file")
|
|
46
|
+
command.add_argument("output")
|
|
47
|
+
command.add_argument("--table", help="name of the table (default: the first one)")
|
|
48
|
+
|
|
49
|
+
command = commands.add_parser("graphs", help="list graph types and analyses for each table type")
|
|
50
|
+
|
|
51
|
+
command = commands.add_parser("schema", help="print the JSON Schema of the file format")
|
|
52
|
+
command.add_argument("--schema-version", type=int, default=SCHEMA_VERSION)
|
|
53
|
+
|
|
54
|
+
arguments = parser.parse_args(argv)
|
|
55
|
+
try:
|
|
56
|
+
return _run(arguments)
|
|
57
|
+
except InvalidProjectError as error:
|
|
58
|
+
print(error, file=sys.stderr)
|
|
59
|
+
return 1
|
|
60
|
+
except (OSError, KeyError, ValueError) as error:
|
|
61
|
+
print(error.args[-1] if error.args else error, file=sys.stderr)
|
|
62
|
+
return 1
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _run(arguments: argparse.Namespace) -> int:
|
|
66
|
+
if arguments.command == "check":
|
|
67
|
+
failed = False
|
|
68
|
+
for file in arguments.file:
|
|
69
|
+
report = check(file)
|
|
70
|
+
if len(arguments.file) > 1:
|
|
71
|
+
print(f"{file}:")
|
|
72
|
+
print(report)
|
|
73
|
+
failed |= bool(report.errors) or (bool(report.warnings) and not arguments.allow_warnings)
|
|
74
|
+
return 1 if failed else 0
|
|
75
|
+
if arguments.command == "tables":
|
|
76
|
+
project = load(arguments.file)
|
|
77
|
+
print(f"{project.title or 'Untitled project'}: {len(project.tables)} table(s)")
|
|
78
|
+
for number, table in enumerate(project.tables, start=1):
|
|
79
|
+
kind = f"{table.format}, derived" if table.derived else table.format
|
|
80
|
+
print(f"{number}. {table.name or '(no name)'} ({kind}): {len(table)} rows")
|
|
81
|
+
if table.data_sets:
|
|
82
|
+
print(f" {', '.join(table.data_sets)}")
|
|
83
|
+
return 0
|
|
84
|
+
if arguments.command == "csv":
|
|
85
|
+
project = load(arguments.file)
|
|
86
|
+
if not project.tables:
|
|
87
|
+
raise ValueError("The project has no tables.")
|
|
88
|
+
table = project.table(arguments.table) if arguments.table else project.tables[0]
|
|
89
|
+
table.to_csv(arguments.output)
|
|
90
|
+
print(f"Wrote {arguments.output}")
|
|
91
|
+
return 0
|
|
92
|
+
if arguments.command == "graphs":
|
|
93
|
+
for table_format in rules()["tables"]:
|
|
94
|
+
print(f"{table_format} tables")
|
|
95
|
+
print(f" graph types: {', '.join(variants_for(table_format))}")
|
|
96
|
+
print(f" analyses: {', '.join(analyses_for(table_format)) or 'none'}")
|
|
97
|
+
return 0
|
|
98
|
+
print(json.dumps(json_schema(arguments.schema_version), indent=2, ensure_ascii=False))
|
|
99
|
+
return 0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
sys.exit(main())
|
pivograph/_check.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Reading and checking project files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from pathlib import Path as FilePath
|
|
10
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
|
|
11
|
+
|
|
12
|
+
from ._report import InvalidProjectError, Issue, Report
|
|
13
|
+
from ._rules import a_table, analyses_for, check_rules, load_data, rules, variants_for
|
|
14
|
+
from ._schema import Path, SchemaValidator, format_path, show
|
|
15
|
+
|
|
16
|
+
PathLike = Union[str, "os.PathLike[str]"]
|
|
17
|
+
_BYTE_ORDER_MARK = chr(0xFEFF)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def check(source: Union[PathLike, Mapping[str, Any]]) -> Report:
|
|
21
|
+
"""Checks a project file (a path) or a document (a dict) and reports every problem."""
|
|
22
|
+
if isinstance(source, Mapping):
|
|
23
|
+
return check_document(source)
|
|
24
|
+
return check_bytes(FilePath(source).read_bytes())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_text(text: str) -> Report:
|
|
28
|
+
"""Checks the text of a project file."""
|
|
29
|
+
return _parse(text)[1]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def check_bytes(data: bytes) -> Report:
|
|
33
|
+
"""Checks the raw content of a project file."""
|
|
34
|
+
return _parse_bytes(data)[1]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def check_document(document: Mapping[str, Any]) -> Report:
|
|
38
|
+
"""Checks a document held in memory as plain Python objects."""
|
|
39
|
+
return _prepare(document)[1]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_document(path: PathLike) -> Tuple[Dict[str, Any], Report]:
|
|
43
|
+
"""Reads a file; raises InvalidProjectError when PivoGraph would not open it."""
|
|
44
|
+
document, report = _parse_bytes(FilePath(path).read_bytes())
|
|
45
|
+
if report.errors or document is None:
|
|
46
|
+
raise InvalidProjectError(report)
|
|
47
|
+
return document, report
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def save(
|
|
51
|
+
document: Mapping[str, Any], path: PathLike, *, allow_warnings: bool = False
|
|
52
|
+
) -> Report:
|
|
53
|
+
"""Writes a document as a project file, unchanged, after checking it.
|
|
54
|
+
|
|
55
|
+
Nothing is written when there is any problem: InvalidProjectError lists all of them. Warnings
|
|
56
|
+
count as problems unless ``allow_warnings`` is True, because they mean that part of the file
|
|
57
|
+
would not take effect as written.
|
|
58
|
+
"""
|
|
59
|
+
target = FilePath(path)
|
|
60
|
+
if target.suffix.lower() != ".pivograph":
|
|
61
|
+
raise ValueError(f'The file name must end with ".pivograph", got "{target.name}".')
|
|
62
|
+
plain, report = _prepare(document)
|
|
63
|
+
if report.errors or plain is None or (report.warnings and not allow_warnings):
|
|
64
|
+
raise InvalidProjectError(report)
|
|
65
|
+
text = json.dumps(plain, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
|
|
66
|
+
target.write_bytes(text.encode("utf-8"))
|
|
67
|
+
return report
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# --- pipeline ---
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _Object(Dict[str, Any]):
|
|
74
|
+
"""A JSON object that remembers keys written more than once."""
|
|
75
|
+
|
|
76
|
+
repeated: Sequence[str] = ()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _parse_bytes(data: bytes) -> Tuple[Optional[Dict[str, Any]], Report]:
|
|
80
|
+
limit = rules()["limits"]["fileBytes"]
|
|
81
|
+
if len(data) > limit:
|
|
82
|
+
return _refuse(f"The file has {len(data)} bytes; the limit is {limit}.")
|
|
83
|
+
try:
|
|
84
|
+
text = data.decode("utf-8")
|
|
85
|
+
except UnicodeDecodeError as error:
|
|
86
|
+
return _refuse(f"The file is not UTF-8 text (byte {error.start}). Save it as UTF-8.")
|
|
87
|
+
return _parse(text)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _parse(text: str) -> Tuple[Optional[Dict[str, Any]], Report]:
|
|
91
|
+
if text.startswith(_BYTE_ORDER_MARK):
|
|
92
|
+
text = text[1:]
|
|
93
|
+
repeated: List[_Object] = []
|
|
94
|
+
|
|
95
|
+
def build(pairs: List[Tuple[str, Any]]) -> _Object:
|
|
96
|
+
built = _Object(pairs)
|
|
97
|
+
if len(built) != len(pairs):
|
|
98
|
+
keys = [key for key, _ in pairs]
|
|
99
|
+
built.repeated = sorted({key for key in keys if keys.count(key) > 1})
|
|
100
|
+
repeated.append(built)
|
|
101
|
+
return built
|
|
102
|
+
|
|
103
|
+
def refuse_constant(name: str) -> Any:
|
|
104
|
+
raise ValueError(f"{name} is not allowed in JSON; use null for a missing value")
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
raw = json.loads(text, object_pairs_hook=build, parse_constant=refuse_constant)
|
|
108
|
+
except json.JSONDecodeError as error:
|
|
109
|
+
return _refuse(_explain(text, error))
|
|
110
|
+
except ValueError as error:
|
|
111
|
+
return _refuse(f"Not valid JSON: {error}.")
|
|
112
|
+
except RecursionError:
|
|
113
|
+
return _refuse("Not valid: the JSON is nested too deeply.")
|
|
114
|
+
document, report = _prepare(raw)
|
|
115
|
+
if repeated:
|
|
116
|
+
for path, keys in _find_repeated(raw):
|
|
117
|
+
for key in keys:
|
|
118
|
+
report.warnings.append(
|
|
119
|
+
Issue(path, f'The key "{key}" is written more than once; only the last one counts.')
|
|
120
|
+
)
|
|
121
|
+
return document, report
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _prepare(raw: Any) -> Tuple[Optional[Dict[str, Any]], Report]:
|
|
125
|
+
"""Envelope, forbidden keys, JSON Schema, then the rules JSON Schema cannot express."""
|
|
126
|
+
problems: List[Issue] = []
|
|
127
|
+
try:
|
|
128
|
+
document = _plain(raw, None, problems)
|
|
129
|
+
except RecursionError:
|
|
130
|
+
return _refuse("Not valid: the document is nested too deeply.")
|
|
131
|
+
if problems:
|
|
132
|
+
return None, Report(errors=problems)
|
|
133
|
+
report = Report()
|
|
134
|
+
project_format = rules()["format"]
|
|
135
|
+
if not isinstance(document, dict):
|
|
136
|
+
return _refuse(f"Expected one JSON object, got {show(document)}.")
|
|
137
|
+
if document.get("format") != project_format:
|
|
138
|
+
found = f"got {show(document['format'])}" if "format" in document else "it is missing"
|
|
139
|
+
report.errors.append(Issue("format", f'It must be "{project_format}"; {found}.'))
|
|
140
|
+
version = document.get("schemaVersion")
|
|
141
|
+
current, minimum = rules()["schemaVersion"], rules()["minimumSchemaVersion"]
|
|
142
|
+
if isinstance(version, bool) or not isinstance(version, (int, float)) or version != int(version):
|
|
143
|
+
found = f"got {show(version)}" if "schemaVersion" in document else "it is missing"
|
|
144
|
+
report.errors.append(
|
|
145
|
+
Issue("schemaVersion", f"It must be the number {current}, without quotes; {found}.")
|
|
146
|
+
)
|
|
147
|
+
elif version > current:
|
|
148
|
+
report.errors.append(
|
|
149
|
+
Issue(
|
|
150
|
+
"schemaVersion",
|
|
151
|
+
f"Version {int(version)} is newer than this package knows ({current}). "
|
|
152
|
+
"Update the package: pip install --upgrade pivograph",
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
elif version < minimum:
|
|
156
|
+
report.errors.append(
|
|
157
|
+
Issue("schemaVersion", f"Version {int(version)} does not exist; use {current}.")
|
|
158
|
+
)
|
|
159
|
+
else:
|
|
160
|
+
report.schema_version = int(version)
|
|
161
|
+
if report.errors:
|
|
162
|
+
return None, report
|
|
163
|
+
assert report.schema_version is not None
|
|
164
|
+
|
|
165
|
+
report.errors.extend(_forbidden_keys(document))
|
|
166
|
+
if not report.errors:
|
|
167
|
+
report.errors.extend(_validator(report.schema_version).errors(document, _Tables(document)))
|
|
168
|
+
if report.errors:
|
|
169
|
+
return None, report
|
|
170
|
+
check_rules(document, report)
|
|
171
|
+
if report.schema_version != current:
|
|
172
|
+
report.notes.append(
|
|
173
|
+
f"The file uses schemaVersion {report.schema_version}; PivoGraph upgrades it to {current} "
|
|
174
|
+
"when it opens it. New files should use the current version."
|
|
175
|
+
)
|
|
176
|
+
return document, report
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _explain(text: str, error: json.JSONDecodeError) -> str:
|
|
180
|
+
message = f"Not valid JSON: {error.msg} at line {error.lineno}, column {error.colno}."
|
|
181
|
+
if text.lstrip().startswith("```"):
|
|
182
|
+
return f"{message} The text starts with a Markdown code fence; keep only the JSON inside it."
|
|
183
|
+
if text.strip() and error.pos >= len(text.rstrip()):
|
|
184
|
+
return f"{message} The text ends before the JSON is complete."
|
|
185
|
+
return f"{message} The file must hold one complete JSON object and nothing else."
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _refuse(message: str) -> Tuple[None, Report]:
|
|
189
|
+
return None, Report(errors=[Issue("(file)", message)])
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _plain(value: Any, path: Path, problems: List[Issue]) -> Any:
|
|
193
|
+
"""Plain JSON values, reporting anything that JSON cannot hold."""
|
|
194
|
+
if value is None or isinstance(value, (str, bool)):
|
|
195
|
+
return value
|
|
196
|
+
if isinstance(value, Mapping):
|
|
197
|
+
result: Dict[str, Any] = {}
|
|
198
|
+
for key, item in value.items():
|
|
199
|
+
if not isinstance(key, str):
|
|
200
|
+
problems.append(Issue(format_path(path), f"Keys must be text, got {key!r}."))
|
|
201
|
+
continue
|
|
202
|
+
result[key] = _plain(item, (path, key), problems)
|
|
203
|
+
return result
|
|
204
|
+
if isinstance(value, (list, tuple)):
|
|
205
|
+
return [_plain(item, (path, index), problems) for index, item in enumerate(value)]
|
|
206
|
+
if not isinstance(value, (int, float)):
|
|
207
|
+
# numpy scalars and arrays convert to plain Python numbers and lists without loss
|
|
208
|
+
convert = getattr(value, "tolist", None)
|
|
209
|
+
converted = convert() if callable(convert) else value
|
|
210
|
+
if isinstance(converted, (int, float, list, str, bool)) and converted is not value:
|
|
211
|
+
return _plain(converted, path, problems)
|
|
212
|
+
problems.append(
|
|
213
|
+
Issue(format_path(path), f"{type(value).__name__} cannot be written as JSON.")
|
|
214
|
+
)
|
|
215
|
+
return None
|
|
216
|
+
try:
|
|
217
|
+
finite = math.isfinite(value)
|
|
218
|
+
except OverflowError:
|
|
219
|
+
finite = False
|
|
220
|
+
if not finite:
|
|
221
|
+
problems.append(
|
|
222
|
+
Issue(
|
|
223
|
+
format_path(path),
|
|
224
|
+
"NaN, infinity and numbers outside the range of a double are not allowed; "
|
|
225
|
+
"use None (null in JSON) for a missing value.",
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
return None
|
|
229
|
+
return int(value) if isinstance(value, int) else float(value)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _forbidden_keys(document: Mapping[str, Any]) -> List[Issue]:
|
|
233
|
+
forbidden = set(rules()["forbiddenKeys"])
|
|
234
|
+
found: List[Issue] = []
|
|
235
|
+
pending: List[Tuple[Any, Path]] = [(document, None)]
|
|
236
|
+
while pending:
|
|
237
|
+
value, path = pending.pop()
|
|
238
|
+
if isinstance(value, list):
|
|
239
|
+
pending.extend(
|
|
240
|
+
(item, (path, index))
|
|
241
|
+
for index, item in enumerate(value)
|
|
242
|
+
if isinstance(item, (dict, list))
|
|
243
|
+
)
|
|
244
|
+
elif isinstance(value, dict):
|
|
245
|
+
for key, item in value.items():
|
|
246
|
+
if key in forbidden:
|
|
247
|
+
found.append(
|
|
248
|
+
Issue(format_path((path, key)), f'The key "{key}" is not allowed.')
|
|
249
|
+
)
|
|
250
|
+
elif isinstance(item, (dict, list)):
|
|
251
|
+
pending.append((item, (path, key)))
|
|
252
|
+
return found
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _find_repeated(raw: Any) -> List[Tuple[str, Sequence[str]]]:
|
|
256
|
+
found: List[Tuple[str, Sequence[str]]] = []
|
|
257
|
+
pending: List[Tuple[Any, Path]] = [(raw, None)]
|
|
258
|
+
while pending:
|
|
259
|
+
value, path = pending.pop()
|
|
260
|
+
if isinstance(value, list):
|
|
261
|
+
pending.extend((item, (path, index)) for index, item in enumerate(value))
|
|
262
|
+
elif isinstance(value, dict):
|
|
263
|
+
repeated = getattr(value, "repeated", ())
|
|
264
|
+
if repeated:
|
|
265
|
+
found.append((format_path(path), repeated))
|
|
266
|
+
pending.extend((item, (path, key)) for key, item in value.items())
|
|
267
|
+
return found
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class _Tables:
|
|
271
|
+
"""Narrows long lists of allowed values to the ones that fit the table at hand."""
|
|
272
|
+
|
|
273
|
+
def __init__(self, document: Mapping[str, Any]) -> None:
|
|
274
|
+
tables = document.get("tables")
|
|
275
|
+
self._tables = tables if isinstance(tables, list) else []
|
|
276
|
+
|
|
277
|
+
def __call__(
|
|
278
|
+
self, path: Path, allowed: Sequence[Any]
|
|
279
|
+
) -> Optional[Tuple[Sequence[Any], str]]:
|
|
280
|
+
segments: List[Any] = []
|
|
281
|
+
while path is not None:
|
|
282
|
+
path, segment = path
|
|
283
|
+
segments.append(segment)
|
|
284
|
+
segments.reverse()
|
|
285
|
+
if len(segments) < 4 or segments[0] != "tables":
|
|
286
|
+
return None
|
|
287
|
+
table = self._tables[segments[1]]
|
|
288
|
+
table_format = table.get("format") if isinstance(table, Mapping) else None
|
|
289
|
+
if not isinstance(table_format, str) or table_format not in rules()["tables"]:
|
|
290
|
+
return None
|
|
291
|
+
if segments[2:] == ["graph", "variantId"]:
|
|
292
|
+
return variants_for(table_format), f"for {a_table(table_format)}"
|
|
293
|
+
if segments[2] == "analyses" and segments[-1] == "method":
|
|
294
|
+
return analyses_for(table_format), f"for {a_table(table_format)}"
|
|
295
|
+
if segments[2:] == ["graph", "plot", "options", "mode"]:
|
|
296
|
+
variant_id = table["graph"].get("variantId")
|
|
297
|
+
variant = rules()["variants"].get(variant_id) if isinstance(variant_id, str) else None
|
|
298
|
+
if variant and variant["table"] == table_format and variant["modes"]:
|
|
299
|
+
return variant["modes"], f'for "{variant_id}"'
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@lru_cache(maxsize=None)
|
|
304
|
+
def _validator(version: int) -> SchemaValidator:
|
|
305
|
+
limits = rules()["limits"]
|
|
306
|
+
return SchemaValidator(
|
|
307
|
+
load_data(f"v{version}.json"),
|
|
308
|
+
record_key_length=limits["recordKeyLength"],
|
|
309
|
+
rich_text_length=limits["richTextLength"],
|
|
310
|
+
usermeta_length=limits["usermetaLength"],
|
|
311
|
+
)
|
pivograph/_hints.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Where a setting really belongs, for the mistakes people and AI assistants make most often."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Iterable, List, Tuple
|
|
6
|
+
|
|
7
|
+
_RAW_VALUES = (
|
|
8
|
+
"PivoGraph computes means, errors and tests from the individual values; "
|
|
9
|
+
"summary statistics cannot be entered."
|
|
10
|
+
)
|
|
11
|
+
_SURVIVAL = (
|
|
12
|
+
'Survival tables keep all times in "x" of the table, one row per subject; each data set holds '
|
|
13
|
+
"1 (event) or 0 (censored) in the rows of its own subjects and null in the other rows."
|
|
14
|
+
)
|
|
15
|
+
_TITLES = 'Titles belong to the table: "titles": {"graph": {"text": "..."}, "x": {...}, "y": {...}}.'
|
|
16
|
+
|
|
17
|
+
# (place, key): the place is the name of the object that holds the key.
|
|
18
|
+
_BY_KEY: Dict[Tuple[str, str], str] = {
|
|
19
|
+
("(root)", "title"): 'The project title is "meta": {"title": "..."}.',
|
|
20
|
+
("(root)", "name"): 'The project title is "meta": {"title": "..."}.',
|
|
21
|
+
("(root)", "data"): 'Data belongs in tables[].dataSets: {"name": "Control", "values": [[1.2], [1.5]]}.',
|
|
22
|
+
("(root)", "graph"): 'A graph belongs to its table: tables[].graph.',
|
|
23
|
+
("(root)", "graphs"): 'A graph belongs to its table: tables[].graph.',
|
|
24
|
+
("tables", "type"): 'The table type is "format".',
|
|
25
|
+
("tables", "family"): 'The table type is "format".',
|
|
26
|
+
("tables", "data"): 'Data belongs in "dataSets": [{"name": "Control", "values": [[1.2], [1.5]]}].',
|
|
27
|
+
("tables", "columns"): 'Data belongs in "dataSets": [{"name": "Control", "values": [[1.2], [1.5]]}].',
|
|
28
|
+
("tables", "groups"): 'Data belongs in "dataSets": [{"name": "Control", "values": [[1.2], [1.5]]}].',
|
|
29
|
+
("tables", "title"): _TITLES,
|
|
30
|
+
("dataSets", "x"): 'X values belong to the table: "x": [0, 1, 2], shared by all data sets.',
|
|
31
|
+
("dataSets", "data"): 'The values of a data set are "values": one inner list per row.',
|
|
32
|
+
("dataSets", "y"): 'The values of a data set are "values": one inner list per row.',
|
|
33
|
+
("graph", "type"): 'The graph type is "variantId".',
|
|
34
|
+
("graph", "axes"): 'Axis settings belong in "axesOverrides": {"leftY": {...}, "xContinuous": {...}}.',
|
|
35
|
+
("graph", "mode"): 'The plot mode is "plot": {"family": "<table format>", "options": {"mode": "..."}}.',
|
|
36
|
+
("graph", "colors"): (
|
|
37
|
+
'Colors belong in "styleOverrides": {"perDataSet": {"<data set name>": {"bar": {"fill": {"hex": "#E64B35"}}}}}.'
|
|
38
|
+
),
|
|
39
|
+
("plot", "mode"): 'It belongs in "options": {"mode": "..."}.',
|
|
40
|
+
("leftY", "min"): 'The axis limits are "rangeMin" and "rangeMax".',
|
|
41
|
+
("leftY", "max"): 'The axis limits are "rangeMin" and "rangeMax".',
|
|
42
|
+
("xContinuous", "min"): 'The axis limits are "rangeMin" and "rangeMax".',
|
|
43
|
+
("xContinuous", "max"): 'The axis limits are "rangeMin" and "rangeMax".',
|
|
44
|
+
("bar", "color"): 'The color of a bar is "fill": {"hex": "#E64B35"}.',
|
|
45
|
+
("legend", "show"): 'It is "visibility".',
|
|
46
|
+
("analyses", "type"): 'The analysis is "method".',
|
|
47
|
+
("annotations", "from"): (
|
|
48
|
+
'A bracket is anchored with "left" and "right": {"kind": "group", "groupIndex": 0}.'
|
|
49
|
+
),
|
|
50
|
+
("annotations", "to"): (
|
|
51
|
+
'A bracket is anchored with "left" and "right": {"kind": "group", "groupIndex": 0}.'
|
|
52
|
+
),
|
|
53
|
+
("annotations", "label"): 'The label is "text".',
|
|
54
|
+
}
|
|
55
|
+
for _place in ("tables", "dataSets"):
|
|
56
|
+
for _key in ("mean", "means", "sd", "sem", "se", "error", "errors", "ci", "n"):
|
|
57
|
+
_BY_KEY[(_place, _key)] = _RAW_VALUES
|
|
58
|
+
for _key in ("time", "times", "event", "events", "status", "censored"):
|
|
59
|
+
_BY_KEY[(_place, _key)] = _SURVIVAL
|
|
60
|
+
for _place in ("graph", "tables"):
|
|
61
|
+
for _key in ("xLabel", "yLabel", "xTitle", "yTitle", "xlabel", "ylabel"):
|
|
62
|
+
_BY_KEY[(_place, _key)] = _TITLES
|
|
63
|
+
_BY_KEY[("graph", "title")] = _TITLES
|
|
64
|
+
_BY_KEY[("graph", "titles")] = _TITLES
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def misplaced(place: str, keys: Iterable[str]) -> str:
|
|
68
|
+
"""Advice for unknown keys found in the object called ``place``, or an empty text."""
|
|
69
|
+
advice: List[str] = []
|
|
70
|
+
for key in keys:
|
|
71
|
+
text = _BY_KEY.get((place, key))
|
|
72
|
+
if text and text not in advice:
|
|
73
|
+
advice.append(text)
|
|
74
|
+
return " ".join(advice)
|