Hyperiso 1.0.3
Modular flavour-physics calculations, Wilson coefficients and statistical inference
Loading...
Searching...
No Matches
DatabaseWriter.py
Go to the documentation of this file.
1"""Export the initialized HyperIso Core database to structured files."""
2
3from __future__ import annotations
4
5import os
6from collections.abc import Iterable
7from pathlib import Path
8from typing import Union
9
10from pyhyperiso.phyperiso.pyhyperiso.core import DatabaseWriter as _CppDatabaseWriter
11from pyhyperiso.core.Common.ParamId import ParamId
12
13PathLike = Union[str, os.PathLike[str]]
14
15
17 """Write current Core parameters as JSON, YAML or Les Houches files.
18
19 The writer operates on the database initialized by :class:`HyperisoMaster`.
20 The destination suffix selects the serializer:
21
22 - ``.json`` for JSON;
23 - ``.yaml`` or ``.yml`` for YAML;
24 - ``.lha``, ``.slha`` or ``.flha`` for Les Houches formats.
25
26 JSON and YAML preserve an optional ``imaginary_value`` field for complex
27 parameters. LHA-family exports preserve complex entries through ``IM...``
28 companion blocks, unless an explicit companion block already exists in the
29 database.
30
31 Examples:
32 >>> writer = DatabaseWriter()
33 >>> writer.write("database.json")
34 >>> writer.write_blocks("masses.yaml", ["MASS", "SMINPUTS"])
35 >>> writer.write_parameters("inputs.slha", [ParamId(block="MASS", code=25)])
36 """
37
38 _SUPPORTED_SUFFIXES = {".json", ".yaml", ".yml", ".lha", ".slha", ".flha"}
39
40 def __init__(self) -> None:
41 """Create a writer bound to the current C++ Core database."""
42 self._cpp_obj = _CppDatabaseWriter()
43
44 @classmethod
45 def _destination(cls, destination: PathLike) -> str:
46 """Validate and normalize an output path for the C++ binding."""
47 path = Path(os.fspath(destination)).expanduser()
48 suffix = path.suffix.lower()
49 if suffix not in cls._SUPPORTED_SUFFIXES:
50 supported = ", ".join(sorted(cls._SUPPORTED_SUFFIXES))
51 raise ValueError(
52 f"Unsupported database export suffix {suffix!r}; expected one of {supported}."
53 )
54 return str(path)
55
56 def write(self, destination: PathLike) -> None:
57 """Export the complete initialized database.
58
59 Args:
60 destination: Output filename. Its suffix selects JSON, YAML or LHA.
61
62 Raises:
63 RuntimeError: If HyperIso has not been initialized or writing fails.
64 ValueError: If the filename suffix is unsupported.
65 """
66 self._cpp_obj.write(self._destination(destination))
67
68 def write_blocks(self, destination: PathLike, block_names: Iterable[str]) -> None:
69 """Export only selected blocks.
70
71 Args:
72 destination: Output filename.
73 block_names: Non-empty iterable of block names or aliases.
74
75 Raises:
76 TypeError: If block names are not supplied as strings.
77 ValueError: If no block is supplied, the suffix is unsupported, or a
78 requested block does not exist.
79 RuntimeError: If HyperIso is not initialized or writing fails.
80 """
81 if isinstance(block_names, (str, bytes)):
82 raise TypeError("block_names must be an iterable of block-name strings")
83 names = list(block_names)
84 if not names:
85 raise ValueError("block_names must not be empty")
86 if not all(isinstance(name, str) for name in names):
87 raise TypeError("block_names must contain only strings")
88 self._cpp_obj.write_blocks(self._destination(destination), names)
89
91 self,
92 destination: PathLike,
93 parameter_ids: Iterable[ParamId],
94 ) -> None:
95 """Export selected parameters addressed by block and LHA identifier.
96
97 Args:
98 destination: Output filename.
99 parameter_ids: Non-empty iterable of :class:`ParamId` objects.
100
101 Raises:
102 TypeError: If an entry is not a ``ParamId``.
103 ValueError: If no parameter is supplied, the suffix is unsupported, or
104 a requested parameter does not exist.
105 RuntimeError: If HyperIso is not initialized or writing fails.
106 """
107 ids = list(parameter_ids)
108 if not ids:
109 raise ValueError("parameter_ids must not be empty")
110 if not all(isinstance(parameter_id, ParamId) for parameter_id in ids):
111 raise TypeError("parameter_ids must contain only ParamId instances")
112
114 self._destination(destination),
115 [parameter_id.to_cpp() for parameter_id in ids],
116 )
117
118
119__all__ = ["DatabaseWriter"]
std::string join(const std::vector< std::string > &v)
Joins a list of strings with ", ".
Definition SourceView.cpp:3
None write_parameters(self, PathLike destination, Iterable[ParamId] parameter_ids)
None write_blocks(self, PathLike destination, Iterable[str] block_names)