calins 1.0.0b2__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.
Files changed (55) hide show
  1. calins/__init__.py +190 -0
  2. calins/_logging.py +232 -0
  3. calins/_version.py +24 -0
  4. calins/analysis/__init__.py +1 -0
  5. calins/analysis/bias.py +322 -0
  6. calins/analysis/comparison.py +210 -0
  7. calins/analysis/screening.py +784 -0
  8. calins/analysis/similarity.py +700 -0
  9. calins/analysis/uncertainty.py +512 -0
  10. calins/assimilation/__init__.py +5 -0
  11. calins/assimilation/gllsm.py +1077 -0
  12. calins/assimilation/usl.py +841 -0
  13. calins/case.py +801 -0
  14. calins/config.py +56 -0
  15. calins/constants.py +16 -0
  16. calins/core/__init__.py +1 -0
  17. calins/core/alignment.py +437 -0
  18. calins/core/linalg.py +41 -0
  19. calins/core/nuclides.py +112 -0
  20. calins/covariances.py +353 -0
  21. calins/data/Logo.PNG +0 -0
  22. calins/data/html.model +95 -0
  23. calins/data/iso_id.json +1 -0
  24. calins/data/reac_id.json +1 -0
  25. calins/datatypes.py +96 -0
  26. calins/exceptions.py +40 -0
  27. calins/io/__init__.py +1 -0
  28. calins/io/covariances/__init__.py +85 -0
  29. calins/io/covariances/comac.py +130 -0
  30. calins/io/covariances/coverx.py +286 -0
  31. calins/io/covariances/gendf.py +234 -0
  32. calins/io/covariances/xlsx.py +86 -0
  33. calins/io/sdf.py +687 -0
  34. calins/plotting/__init__.py +1 -0
  35. calins/plotting/figures.py +511 -0
  36. calins/plotting/helpers.py +398 -0
  37. calins/reporting/__init__.py +1 -0
  38. calins/reporting/assimilation_report.py +1652 -0
  39. calins/reporting/case_report.py +129 -0
  40. calins/reporting/html.py +158 -0
  41. calins/reporting/uncertainty_report.py +336 -0
  42. calins/src/__init__.py +51 -0
  43. calins/src/class_plot_helpers.py +7 -0
  44. calins/src/classes.py +24 -0
  45. calins/src/errors.py +14 -0
  46. calins/src/logs.py +13 -0
  47. calins/src/methods.py +58 -0
  48. calins/src/plots.py +26 -0
  49. calins/src/version.py +7 -0
  50. calins/version.py +18 -0
  51. calins-1.0.0b2.dist-info/METADATA +586 -0
  52. calins-1.0.0b2.dist-info/RECORD +55 -0
  53. calins-1.0.0b2.dist-info/WHEEL +5 -0
  54. calins-1.0.0b2.dist-info/licenses/LICENSE +29 -0
  55. calins-1.0.0b2.dist-info/top_level.txt +1 -0
calins/__init__.py ADDED
@@ -0,0 +1,190 @@
1
+ """CALINS - CALculations and Investigations on Nuclear data uncertainties and Sensitivities.
2
+
3
+ Public API::
4
+
5
+ import calins as cl
6
+
7
+ case = cl.Case("my_case.sdf")
8
+ cov = cl.NDCovariances("my_covariances.coverx")
9
+ unc = cl.calcul_uncertainty(case, cov)
10
+
11
+ Options are set through :data:`calins.config` (``verbose``, ``offline_export``, ``log_dir``).
12
+ """
13
+
14
+ import importlib
15
+ import warnings
16
+
17
+ from .analysis.bias import Bias, calcul_bias
18
+ from .analysis.comparison import (
19
+ compare_row,
20
+ compare_sensitivities,
21
+ is_values_in_agreement,
22
+ )
23
+ from .analysis.screening import (
24
+ build_sensitive_dataframe,
25
+ display_dataframe,
26
+ display_most_sensitive_cases,
27
+ filter_cases,
28
+ filter_common_data,
29
+ find_sensitive_cases,
30
+ find_sensitive_cases_for_combination,
31
+ plot_sensitivity_heatmap,
32
+ sort_case_sensitivities,
33
+ )
34
+ from .analysis.similarity import calcul_Ck, calcul_E, calcul_G, calcul_G_CEA, calcul_SSR
35
+ from .analysis.uncertainty import Uncertainty, calcul_uncertainty
36
+ from .assimilation import Assimilation
37
+ from .case import Case
38
+ from .config import config
39
+ from .constants import iso_z, iso_z_inv, reac_trad, reac_trad_inv
40
+ from .core.alignment import (
41
+ check_correspondences,
42
+ check_dimmensions,
43
+ get_common_iso_reac_list,
44
+ make_cov_matrix,
45
+ make_sensi_vectors,
46
+ make_sensi_vectors_and_cov_matrix,
47
+ )
48
+ from .core.nuclides import (
49
+ convert_iso_id_to_string,
50
+ convert_iso_string_to_id,
51
+ normalize_iso_reac,
52
+ )
53
+ from .covariances import NDCovariances
54
+ from .datatypes import CovarianceData, SensitivityData, SimilarityResult, USLResult
55
+ from .exceptions import (
56
+ CalinsError,
57
+ DimError,
58
+ EmptyParsingError,
59
+ MissingDataError,
60
+ SensInputError,
61
+ UserInputError,
62
+ )
63
+ from .io.covariances import (
64
+ format_comac_to_dataframe,
65
+ format_gendf_to_dataframe,
66
+ format_scale_binary_to_dataframe,
67
+ format_scale_corr_to_dataframe,
68
+ format_scale_txt_to_dataframe,
69
+ format_xlsx_to_dataframe,
70
+ read_covariances,
71
+ )
72
+ from .io.sdf import condense_binning, condense_sdf, format_sensi_to_dataframe, read_sdf
73
+ from .version import __version__
74
+
75
+ __all__ = [
76
+ "__version__",
77
+ "config",
78
+ # constants
79
+ "reac_trad",
80
+ "reac_trad_inv",
81
+ "iso_z",
82
+ "iso_z_inv",
83
+ # exceptions
84
+ "CalinsError",
85
+ "EmptyParsingError",
86
+ "DimError",
87
+ "SensInputError",
88
+ "UserInputError",
89
+ "MissingDataError",
90
+ # data model
91
+ "CovarianceData",
92
+ "SensitivityData",
93
+ "SimilarityResult",
94
+ "USLResult",
95
+ # classes
96
+ "Case",
97
+ "NDCovariances",
98
+ "Assimilation",
99
+ "Uncertainty",
100
+ "Bias",
101
+ # file formats
102
+ "read_sdf",
103
+ "format_sensi_to_dataframe",
104
+ "condense_binning",
105
+ "condense_sdf",
106
+ "read_covariances",
107
+ "format_comac_to_dataframe",
108
+ "format_gendf_to_dataframe",
109
+ "format_scale_corr_to_dataframe",
110
+ "format_scale_binary_to_dataframe",
111
+ "format_scale_txt_to_dataframe",
112
+ "format_xlsx_to_dataframe",
113
+ # nuclides and alignment
114
+ "convert_iso_id_to_string",
115
+ "convert_iso_string_to_id",
116
+ "normalize_iso_reac",
117
+ "make_cov_matrix",
118
+ "get_common_iso_reac_list",
119
+ "make_sensi_vectors",
120
+ "make_sensi_vectors_and_cov_matrix",
121
+ "check_dimmensions",
122
+ "check_correspondences",
123
+ # analyses
124
+ "calcul_E",
125
+ "calcul_SSR",
126
+ "calcul_G_CEA",
127
+ "calcul_G",
128
+ "calcul_Ck",
129
+ "calcul_uncertainty",
130
+ "calcul_bias",
131
+ "compare_sensitivities",
132
+ "compare_row",
133
+ "is_values_in_agreement",
134
+ "filter_cases",
135
+ "filter_common_data",
136
+ "find_sensitive_cases_for_combination",
137
+ "find_sensitive_cases",
138
+ "build_sensitive_dataframe",
139
+ "display_most_sensitive_cases",
140
+ "plot_sensitivity_heatmap",
141
+ "sort_case_sensitivities",
142
+ "display_dataframe",
143
+ ]
144
+
145
+ # Former sub-modules (calins.methods, calins.classes, ...) are still reachable through the
146
+ # deprecated ``calins.src`` compatibility package.
147
+ _DEPRECATED_MODULES = {
148
+ "methods",
149
+ "classes",
150
+ "plots",
151
+ "logs",
152
+ "errors",
153
+ "class_plot_helpers",
154
+ }
155
+
156
+ # Names formerly exported at the top level that now live in an internal module.
157
+ _DEPRECATED_NAMES = {
158
+ "log_exec": "calins._logging",
159
+ "warn": "calins._logging",
160
+ "write_and_print": "calins._logging",
161
+ "color_map_reac": "calins.plotting.figures",
162
+ "plot_integrals_per_iso_reac": "calins.plotting.figures",
163
+ "plot_profiles_per_iso_reac": "calins.plotting.figures",
164
+ "plot_matrix_integrals_per_iso_reac": "calins.plotting.figures",
165
+ "plot_submatrix": "calins.plotting.figures",
166
+ "plot_specific_covariance_matrix": "calins.plotting.figures",
167
+ "html_setup": "calins.reporting.html",
168
+ "create_html_tabs": "calins.reporting.html",
169
+ "create_html_tip": "calins.reporting.html",
170
+ "apply_interactive_report_layout": "calins.reporting.html",
171
+ "create_html_table": "calins.reporting.html",
172
+ }
173
+
174
+
175
+ def __getattr__(name):
176
+ if name in _DEPRECATED_MODULES:
177
+ return importlib.import_module(f"calins.src.{name}")
178
+ if name in _DEPRECATED_NAMES:
179
+ module = _DEPRECATED_NAMES[name]
180
+ warnings.warn(
181
+ f"'calins.{name}' is deprecated, use '{module}.{name}' instead.",
182
+ DeprecationWarning,
183
+ stacklevel=2,
184
+ )
185
+ return getattr(importlib.import_module(module), name)
186
+ raise AttributeError(f"module 'calins' has no attribute '{name}'")
187
+
188
+
189
+ def __dir__():
190
+ return sorted(set(globals()) | _DEPRECATED_MODULES)
calins/_logging.py ADDED
@@ -0,0 +1,232 @@
1
+ """CALINS logging, built on the standard :mod:`logging` module.
2
+
3
+ Every message goes to the ``calins`` logger, which has two handlers:
4
+
5
+ * a file handler writing ``<config.log_dir>/CALINS_<YYYY-MM-DD>.log`` (always active);
6
+ * a terminal handler printing ``[CALINS] ...`` when ``config.verbose`` is ``True``
7
+ (or when the message bypasses the verbosity).
8
+
9
+ Additional handlers can be attached by the user with ``logging.getLogger("calins")``.
10
+ """
11
+
12
+ import inspect
13
+ import logging
14
+ import os
15
+ import re
16
+ import sys
17
+ import time
18
+ from functools import wraps
19
+
20
+ from .config import config
21
+ from .version import __version__
22
+
23
+ __all__ = ["logger", "log_exec", "warn", "write_and_print", "write_in_log"]
24
+
25
+ LOGGER_NAME = "calins"
26
+
27
+ logger = logging.getLogger(LOGGER_NAME)
28
+ logger.setLevel(logging.INFO)
29
+ logger.propagate = False
30
+
31
+ _session_started = False
32
+ _prepared_log_dir = None
33
+
34
+
35
+ def _prefix(record):
36
+ return "" if record.levelno == logging.INFO else f"{record.levelname} : "
37
+
38
+
39
+ class _FileFormatter(logging.Formatter):
40
+ def format(self, record):
41
+ return f"{time.strftime('%H:%M:%S', time.localtime(record.created))} - {_prefix(record)}{record.getMessage()}"
42
+
43
+
44
+ class _TerminalFormatter(logging.Formatter):
45
+ def format(self, record):
46
+ return f"[CALINS] {_prefix(record)}{record.getMessage()}"
47
+
48
+
49
+ def _prepare_log_dir():
50
+ """Create the log directory and remove the oldest log files (once per directory)."""
51
+ global _prepared_log_dir
52
+
53
+ log_dir = config.resolved_log_dir
54
+ if _prepared_log_dir == log_dir and os.path.isdir(log_dir):
55
+ return log_dir
56
+ os.makedirs(log_dir, exist_ok=True)
57
+ _prepared_log_dir = log_dir
58
+
59
+ log_files = [
60
+ os.path.join(root, file)
61
+ for root, _dirs, files in os.walk(log_dir)
62
+ for file in files
63
+ if file.endswith(".log")
64
+ ]
65
+ if len(log_files) > config.max_log_files:
66
+ write_and_print(
67
+ f"Log directory {log_dir} contains too many files ({len(log_files)} > max log file nb ({config.max_log_files})), removing oldest log files.",
68
+ "WARNING",
69
+ )
70
+ log_files.sort(key=os.path.getctime)
71
+ for path in log_files[: len(log_files) - config.max_log_files]:
72
+ os.remove(path)
73
+ return log_dir
74
+
75
+
76
+ class _DailyFileHandler(logging.Handler):
77
+ """Append the records to ``<config.log_dir>/CALINS_<date>.log``.
78
+
79
+ The directory is resolved at each record so that ``config.log_dir`` can be changed at any time.
80
+ """
81
+
82
+ def emit(self, record):
83
+ try:
84
+ path = os.path.join(
85
+ _prepare_log_dir(), f"CALINS_{time.strftime('%Y-%m-%d')}.log"
86
+ )
87
+ with open(path, "a", encoding="utf-8") as f:
88
+ f.write(self.format(record) + "\n")
89
+ except Exception:
90
+ self.handleError(record)
91
+
92
+
93
+ class _TerminalHandler(logging.Handler):
94
+ """Print the records on the current ``sys.stdout``, without failing on a legacy terminal encoding."""
95
+
96
+ def filter(self, record):
97
+ if getattr(record, "calins_file_only", False):
98
+ return False
99
+ return config.verbose or getattr(record, "calins_bypass_verbose", False)
100
+
101
+ def emit(self, record):
102
+ message = self.format(record)
103
+ try:
104
+ print(message)
105
+ except UnicodeEncodeError:
106
+ encoding = sys.stdout.encoding or "utf-8"
107
+ print(message.encode(encoding, errors="backslashreplace").decode(encoding))
108
+ except Exception:
109
+ self.handleError(record)
110
+
111
+
112
+ if not any(isinstance(h, _DailyFileHandler) for h in logger.handlers):
113
+ _file_handler = _DailyFileHandler()
114
+ _file_handler.setFormatter(_FileFormatter())
115
+ logger.addHandler(_file_handler)
116
+ _terminal_handler = _TerminalHandler()
117
+ _terminal_handler.setFormatter(_TerminalFormatter())
118
+ logger.addHandler(_terminal_handler)
119
+
120
+
121
+ _LEVELS = {
122
+ None: logging.INFO,
123
+ "INFO": logging.INFO,
124
+ "WARNING": logging.WARNING,
125
+ "ERROR": logging.ERROR,
126
+ }
127
+
128
+
129
+ def _big_header():
130
+ len_header = 90
131
+ first_line = f"{len_header * '_'}" + "\n" + f"|{(len_header - 2) * ' '}|"
132
+ end_line = f"|{(len_header - 2) * '_'}|"
133
+ info_str = f"(package : calins v. {__version__}) - python session"
134
+ return (
135
+ "\n"
136
+ + first_line
137
+ + "\n"
138
+ + "CALINS".center(len_header)
139
+ + "\n"
140
+ + info_str.center(len_header)
141
+ + "\n"
142
+ + end_line
143
+ + "\n"
144
+ )
145
+
146
+
147
+ def ensure_session():
148
+ """Write the session header once per Python session."""
149
+ global _session_started
150
+
151
+ if not _session_started:
152
+ _session_started = True
153
+ logger.info(_big_header(), extra={"calins_bypass_verbose": True})
154
+
155
+
156
+ def write_and_print(msg, type=None, bypass_verbose=False):
157
+ """Write a message in the log file and print it in the terminal (if ``config.verbose``)."""
158
+ ensure_session()
159
+ logger.log(
160
+ _LEVELS.get(type, logging.INFO),
161
+ msg,
162
+ extra={"calins_bypass_verbose": bypass_verbose},
163
+ )
164
+
165
+
166
+ def write_in_log(msg, type=None):
167
+ """Write a message in the log file only."""
168
+ ensure_session()
169
+ logger.log(_LEVELS.get(type, logging.INFO), msg, extra={"calins_file_only": True})
170
+
171
+
172
+ def warn(msg, bypass_verbose=False):
173
+ write_and_print(msg, "WARNING", bypass_verbose=bypass_verbose)
174
+
175
+
176
+ _PATH_OR_CASE = re.compile("path|case")
177
+ _DETAILED_ARGS = re.compile("iso|reac|threshold|normalize|integrate|energy")
178
+ _RETURN_EXCEPTIONS = ("USL", "plot")
179
+
180
+
181
+ def _format_args(signature, args, kwargs, tab_str):
182
+ arg_str = ""
183
+ for key, val in signature.bind(*args, **kwargs).arguments.items():
184
+ if _PATH_OR_CASE.search(key) and isinstance(val, str):
185
+ arg_str += f"\n{11 * ' '}{tab_str} {key}={val}"
186
+ elif "case" in key and val.__class__.__name__ == "Case":
187
+ arg_str += f"\n{11 * ' '}{tab_str} {key}=(Case){val.sdf_path}"
188
+ elif _DETAILED_ARGS.search(key):
189
+ arg_str += f"\n{11 * ' '}{tab_str} {key}={val}"
190
+ return arg_str
191
+
192
+
193
+ def log_exec():
194
+ """Decorator logging the call (and the main arguments) of a CALINS function or method."""
195
+
196
+ def log_exec_deco(func):
197
+ signature = inspect.signature(func)
198
+ is_method = "." in func.__qualname__ and "<locals>" not in func.__qualname__
199
+ is_init = func.__name__ == "__init__"
200
+ is_calcul = "calcul" in func.__name__ and not any(
201
+ exc in func.__name__ for exc in _RETURN_EXCEPTIONS
202
+ )
203
+
204
+ @wraps(func)
205
+ def log_exec_wrapper(*args, **kwargs):
206
+ caller = sys._getframe(1).f_code.co_name
207
+
208
+ if is_method and args:
209
+ tab_str = "" if is_init else 2 * " "
210
+ parent_str = f"{tab_str}{type(args[0]).__name__} - "
211
+ else:
212
+ tab_str = ""
213
+ parent_str = ""
214
+
215
+ if "calcul_bias" not in caller:
216
+ write_and_print(
217
+ f"{parent_str}{func.__name__}: {_format_args(signature, args, kwargs, tab_str)}"
218
+ )
219
+
220
+ ret = func(*args, **kwargs)
221
+
222
+ if is_calcul and "calcul" not in caller:
223
+ shown = (
224
+ ret.value if type(ret).__name__ in ("Uncertainty", "Bias") else ret
225
+ )
226
+ write_and_print(f"{tab_str} -> {shown}")
227
+
228
+ return ret
229
+
230
+ return log_exec_wrapper
231
+
232
+ return log_exec_deco
calins/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '1.0.0b2'
22
+ __version_tuple__ = version_tuple = (1, 0, 0, 'b2')
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1 @@
1
+ """Analyses on sensitivity cases: similarity indices, uncertainty, bias, comparison, screening."""