kipe 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.
kipe/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """kipe: Kalman-based identifiability and parameter estimation."""
2
+
3
+ from importlib import metadata
4
+
5
+ __version__ = metadata.version("kipe") # from the git tags at install time (hatch-vcs)
kipe/_formatting.py ADDED
@@ -0,0 +1,27 @@
1
+ """Text formatting for the command line and log output."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+
6
+ def format_table(rows: Sequence[Sequence[str]], align: str | None = None) -> list[str]:
7
+ """Align the cells of a table in columns, two spaces apart.
8
+
9
+ Args:
10
+ rows: the rows, the first one is the header; shorter rows are padded with empty cells
11
+ align: one character per column, ``"<"`` (left) or ``">"`` (right); all left if not
12
+ given
13
+
14
+ Returns:
15
+ the lines of the table, without trailing whitespace
16
+ """
17
+ n = max(len(row) for row in rows)
18
+ padded = [list(row) + [""] * (n - len(row)) for row in rows]
19
+ widths = [max(len(row[i]) for row in padded) for i in range(n)]
20
+ alignments = align or "<" * n
21
+
22
+ return [
23
+ " ".join(
24
+ f"{cell:{a}{w}}" for cell, a, w in zip(row, alignments, widths, strict=True)
25
+ ).rstrip()
26
+ for row in padded
27
+ ]
kipe/_types.py ADDED
@@ -0,0 +1,6 @@
1
+ """Array types used throughout kipe."""
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ type NDArray_f64 = npt.NDArray[np.float64]
kipe/_yaml.py ADDED
@@ -0,0 +1,24 @@
1
+ """Writing YAML files: the study file and the provenance of a run."""
2
+
3
+ from collections.abc import Mapping
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from ruamel.yaml import YAML
8
+
9
+
10
+ def write_yaml(path: str | Path, data: Mapping[str, Any]) -> None:
11
+ """Write a mapping as YAML: block style, one line per value, ``null`` for None.
12
+
13
+ Args:
14
+ path: where to write
15
+ data: the mapping
16
+ """
17
+ yaml = YAML()
18
+ yaml.default_flow_style = False
19
+ yaml.width = 4096 # one line per value, no wrapping
20
+ yaml.representer.add_representer( # write "null", not an empty value
21
+ type(None), lambda r, _: r.represent_scalar("tag:yaml.org,2002:null", "null")
22
+ )
23
+ with open(path, "w") as f:
24
+ yaml.dump(dict(data), f)
kipe/cli.py ADDED
@@ -0,0 +1,307 @@
1
+ """Command line interface: ``kipe <subcommand> study.yaml``."""
2
+
3
+ import argparse
4
+ import logging
5
+ import sys
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+
9
+ from mpi4py import MPI
10
+
11
+ from pydantic import ValidationError
12
+
13
+ from kipe._formatting import format_table
14
+ from kipe.estimation import estimate
15
+ from kipe.forward_solver import ForwardSolverError, build_forward_solver
16
+ from kipe.options import StudyFileError, StudyOptions, load_study
17
+ from kipe.parameters import build_parameterization
18
+ from kipe.plot import (
19
+ PlotError,
20
+ plot_histories,
21
+ read_history,
22
+ render_histories,
23
+ watch_histories,
24
+ )
25
+ from kipe.synthesis import synthesize
26
+
27
+
28
+ def main(argv: Sequence[str] | None = None) -> int:
29
+ """Run the kipe command line interface.
30
+
31
+ Args:
32
+ argv: command line arguments without the program name; ``sys.argv[1:]`` if not given
33
+
34
+ Returns:
35
+ exit code
36
+ """
37
+ parser = argparse.ArgumentParser(prog="kipe", description=__doc__)
38
+ subparsers = parser.add_subparsers(dest="command", required=True)
39
+
40
+ list_parameters = subparsers.add_parser(
41
+ "list-parameters",
42
+ help="list the estimable parameters of the forward solver and their nominal values",
43
+ )
44
+ list_parameters.add_argument("study", type=Path, help="study file (YAML)")
45
+ list_parameters.set_defaults(func=_list_parameters)
46
+
47
+ synthesis = subparsers.add_parser(
48
+ "synthesis",
49
+ aliases=["synthesize"],
50
+ help="generate synthetic measurement data from a forward run",
51
+ )
52
+ synthesis.add_argument("study", type=Path, help="study file (YAML)")
53
+ _add_log_level_argument(synthesis)
54
+ synthesis.set_defaults(func=_synthesis)
55
+
56
+ estimation = subparsers.add_parser(
57
+ "estimation",
58
+ aliases=["estimate"],
59
+ help="estimate the parameters from the measurement data",
60
+ )
61
+ estimation.add_argument("study", type=Path, help="study file (YAML)")
62
+ _add_log_level_argument(estimation)
63
+ estimation.set_defaults(func=_estimation)
64
+
65
+ plot = subparsers.add_parser(
66
+ "plot",
67
+ help="plot the estimation history: the estimates with their 1σ range",
68
+ )
69
+ plot.add_argument(
70
+ "studies",
71
+ type=Path,
72
+ nargs="+",
73
+ metavar="study",
74
+ help="study file(s) (YAML); several are plotted into the same figure",
75
+ )
76
+ plot.add_argument(
77
+ "--truth",
78
+ action="store_true",
79
+ help="draw the nominal parameters of the first study's forward solver as reference",
80
+ )
81
+ plot.add_argument("--save", type=Path, metavar="FILE", help="save the figure, don't show it")
82
+ plot.add_argument(
83
+ "--terminal", action="store_true", help="draw the plot as text in the terminal"
84
+ )
85
+ plot.add_argument(
86
+ "--watch",
87
+ action="store_true",
88
+ help="redraw in the terminal as the estimation runs, until Ctrl+C; implies --terminal",
89
+ )
90
+ plot.add_argument(
91
+ "--interval",
92
+ type=float,
93
+ default=2.0,
94
+ metavar="SECONDS",
95
+ help="time between redraws with --watch (default: %(default)s)",
96
+ )
97
+ plot.set_defaults(func=_plot)
98
+
99
+ args = parser.parse_args(argv)
100
+ if args.command == "plot" and args.save and (args.terminal or args.watch):
101
+ plot.error("--save writes a matplotlib figure, not with --terminal or --watch")
102
+
103
+ try:
104
+ args.func(args)
105
+ except (StudyFileError, ForwardSolverError, PlotError) as err: # user errors: no traceback
106
+ print(f"kipe: error: {err}", file=sys.stderr)
107
+ return 1
108
+
109
+ return 0
110
+
111
+
112
+ def _load_study(path: Path) -> StudyOptions:
113
+ """Read and validate a study file, reporting invalid options as a user error.
114
+
115
+ Args:
116
+ path: path to the study file
117
+
118
+ Returns:
119
+ validated study options
120
+
121
+ Raises:
122
+ StudyFileError: if the file cannot be read, or its options are invalid; the message
123
+ lists each invalid option
124
+ """
125
+ try:
126
+ return load_study(path)
127
+ except ValidationError as err:
128
+ lines = [f"invalid study file {path}"]
129
+ for error in err.errors(include_url=False):
130
+ location = ".".join(map(str, error["loc"]))
131
+ lines.append(f" {location}: {error['msg']}")
132
+ raise StudyFileError("\n".join(lines)) from err
133
+
134
+
135
+ def _list_parameters(args: argparse.Namespace) -> None:
136
+ """Print the solver's estimable parameters and their nominal values.
137
+
138
+ If the study file selects parameters, also print their initial estimate, standard
139
+ deviation and the resulting physical 1σ range.
140
+
141
+ Args:
142
+ args: parsed command line arguments, with the path to the study file
143
+ """
144
+ study = _load_study(args.study)
145
+ solver = build_forward_solver(study.forward_solver)
146
+ nominal = solver.nominal_parameters()
147
+
148
+ selected: dict[str, tuple[str, str, str, str]] = {}
149
+
150
+ if study.parameters is not None:
151
+ parameterization = build_parameterization(study.parameters, nominal)
152
+ ranges = parameterization.one_sigma_range()
153
+
154
+ for parameter, (lower, upper) in zip(parameterization.parameters, ranges, strict=True):
155
+ prior = study.parameters.select[parameter.name]
156
+ if prior.relative_stddev is not None:
157
+ stddev = f"{prior.relative_stddev:.3g} (relative)"
158
+ else:
159
+ stddev = f"{prior.stddev:g}"
160
+
161
+ selected[parameter.name] = (
162
+ parameter.reparameterization,
163
+ f"{parameter.initial:g}",
164
+ stddev,
165
+ f"[{lower:.3g}, {upper:.3g}]",
166
+ )
167
+
168
+ rows: list[tuple[str, ...]] = [
169
+ ("parameter", "nominal", "reparameterization", "initial", "stddev", "1σ range")
170
+ ]
171
+
172
+ for name, value in nominal.items():
173
+ rows.append((name, f"{value:g}", *selected.get(name, ("", "", "", ""))))
174
+
175
+ if not selected:
176
+ rows = [row[:2] for row in rows]
177
+
178
+ for line in format_table(rows):
179
+ print(line)
180
+
181
+
182
+ def _synthesis(args: argparse.Namespace) -> None:
183
+ """Generate the measurement data of the study.
184
+
185
+ Args:
186
+ args: parsed command line arguments, with the path to the study file
187
+ """
188
+ study = _load_study(args.study)
189
+ log_file = Path(study.output.path) / "synthesis" / "kipe.log"
190
+ _setup_logging(args.log_level or study.output.log_level, log_file)
191
+ logging.getLogger("kipe").info("%-11s%s", "study", args.study.resolve())
192
+ synthesize(study)
193
+ logging.getLogger("kipe").info("%-11s%s", "log", log_file)
194
+
195
+
196
+ def _estimation(args: argparse.Namespace) -> None:
197
+ """Estimate the parameters of the study.
198
+
199
+ Args:
200
+ args: parsed command line arguments, with the path to the study file
201
+ """
202
+ study = _load_study(args.study)
203
+ log_file = Path(study.output.path) / "estimation" / "kipe.log"
204
+ _setup_logging(args.log_level or study.output.log_level, log_file)
205
+ logging.getLogger("kipe").info("%-11s%s", "study", args.study.resolve())
206
+ estimate(study)
207
+ logging.getLogger("kipe").info("%-11s%s", "log", log_file)
208
+
209
+
210
+ def _plot(args: argparse.Namespace) -> None:
211
+ """Plot the estimation history of one or several studies.
212
+
213
+ Args:
214
+ args: parsed command line arguments: the study files and the plot options
215
+
216
+ Raises:
217
+ PlotError: if matplotlib or plotext is not installed, or a history cannot be read
218
+ """
219
+ studies = [_load_study(path) for path in args.studies]
220
+ paths = {
221
+ str(path): Path(study.output.path) / "estimation" / "history.csv"
222
+ for path, study in zip(args.studies, studies, strict=True)
223
+ }
224
+
225
+ truth = None
226
+ if args.truth:
227
+ truth = build_forward_solver(studies[0].forward_solver).nominal_parameters()
228
+
229
+ if args.watch:
230
+ watch_histories(paths, truth, args.interval)
231
+ return
232
+
233
+ histories = {label: read_history(path) for label, path in paths.items()}
234
+
235
+ if args.terminal:
236
+ print(render_histories(histories, truth, color=sys.stdout.isatty()))
237
+ return
238
+
239
+ try:
240
+ import matplotlib.pyplot as plt
241
+ from matplotlib.figure import Figure
242
+ except ImportError as err:
243
+ raise PlotError("kipe plot needs matplotlib: pip install 'kipe[plot]'") from err
244
+
245
+ figure = Figure(layout="constrained") if args.save else plt.figure(layout="constrained")
246
+ figure.set_size_inches(4 * len(next(iter(histories.values())).names), 3.5)
247
+ plot_histories(figure, histories, truth)
248
+ if args.save:
249
+ figure.savefig(args.save, dpi=150)
250
+ else:
251
+ plt.show()
252
+
253
+
254
+ def _add_log_level_argument(parser: argparse.ArgumentParser) -> None:
255
+ """Add the ``--log-level`` option, which overrides ``output.log_level`` of the study file.
256
+
257
+ Args:
258
+ parser: parser of a subcommand
259
+ """
260
+ parser.add_argument(
261
+ "--log-level",
262
+ choices=["debug", "info", "warning", "error"],
263
+ help="minimum level of the log messages; overrides output.log_level of the study file",
264
+ )
265
+
266
+
267
+ def _setup_logging(level: str, log_file: Path) -> None:
268
+ """Send kipe's log messages to stderr and, in full detail, to a log file.
269
+
270
+ On stderr, MPI rank 0 reports from the given level on; the other ranks only report warnings
271
+ and errors, marked with their rank. At the debug level, each message shows where it was
272
+ logged. Rank 0 also writes all messages, from the debug level on and with their location, to
273
+ ``log_file`` (overwritten).
274
+
275
+ Args:
276
+ level: minimum level of the messages on stderr of rank 0, e.g., ``"info"``
277
+ log_file: path of the log file
278
+ """
279
+ rank = MPI.COMM_WORLD.rank
280
+ prefix = "kipe" if rank == 0 else f"kipe[{rank}]"
281
+ location = "%(module)s:%(funcName)s:%(lineno)d "
282
+
283
+ logger = logging.getLogger("kipe")
284
+ for handler in list(logger.handlers): # main() may run several times in one process
285
+ logger.removeHandler(handler)
286
+ handler.close()
287
+
288
+ console = logging.StreamHandler()
289
+ console.setFormatter(
290
+ logging.Formatter(f"{prefix}: {location if level == 'debug' else ''}%(message)s")
291
+ )
292
+ console.setLevel(level.upper() if rank == 0 else logging.WARNING)
293
+ logger.addHandler(console)
294
+
295
+ if rank == 0:
296
+ log_file.parent.mkdir(parents=True, exist_ok=True)
297
+ file = logging.FileHandler(log_file, mode="w", encoding="utf-8")
298
+ file.setFormatter(
299
+ logging.Formatter(f"%(asctime)s %(levelname)-7s {location}%(message)s")
300
+ )
301
+ logger.addHandler(file)
302
+
303
+ logger.setLevel(logging.DEBUG if rank == 0 else logging.WARNING)
304
+
305
+
306
+ if __name__ == "__main__":
307
+ sys.exit(main())