graspkit-atomic 3.5.2__tar.gz → 3.6.0__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.
Files changed (52) hide show
  1. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/.gitignore +4 -0
  2. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/INSTALL.md +12 -12
  3. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/PKG-INFO +9 -10
  4. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/README.md +8 -9
  5. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/README_zh.md +7 -7
  6. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/docs/csf-selection-primitives.md +31 -2
  7. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/docs/releasing.md +24 -11
  8. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/__init__.py +4 -0
  9. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/coupling.py +153 -113
  10. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/validation.py +3 -1
  11. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/version.py +1 -1
  12. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit_plot/__init__.py +2 -0
  13. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit_plot/mid_coupling.py +116 -27
  14. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/LICENSE +0 -0
  15. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/build_package.py +0 -0
  16. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/pyproject.toml +0 -0
  17. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/scripts/check_release.py +0 -0
  18. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/coverage.py +0 -0
  19. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/extraction.py +0 -0
  20. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/mr_selection.py +0 -0
  21. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/CSFs_processor/selection.py +0 -0
  22. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/__init__.py +0 -0
  23. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/__init__.py +0 -0
  24. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/file_locator.py +0 -0
  25. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/__init__.py +0 -0
  26. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/base_loader.py +0 -0
  27. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/binary_file_loader.py +0 -0
  28. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/energy_file_loader.py +0 -0
  29. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/gj_factor_loader.py +0 -0
  30. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/hyperfine_structure_loader.py +0 -0
  31. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/lsj_comp_loader.py +0 -0
  32. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/mix_coef_loader.py +0 -0
  33. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/radial_analysis_loader.py +0 -0
  34. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/radial_wavefunction_loader.py +0 -0
  35. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/loaders/transition_loader.py +0 -0
  36. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/mix_coef_writer.py +0 -0
  37. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/data_IO/produced_data_writor.py +0 -0
  38. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/__init__.py +0 -0
  39. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/asfs_data_processor.py +0 -0
  40. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/radial_analysis.py +0 -0
  41. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/radial_wavefunction_processor.py +0 -0
  42. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/rmix_data_processor.py +0 -0
  43. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/grasp_data_extractor/transition_data_processor.py +0 -0
  44. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/py.typed +0 -0
  45. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/utils/__init__.py +0 -0
  46. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/utils/data_modules.py +0 -0
  47. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/utils/environment_config.py +0 -0
  48. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/utils/quadrupole_deformation.py +0 -0
  49. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit/utils/tool_function.py +0 -0
  50. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit_plot/fig_settings.py +0 -0
  51. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit_plot/plot_functions.py +0 -0
  52. {graspkit_atomic-3.5.2 → graspkit_atomic-3.6.0}/src/graspkit_plot/radial_analysis.py +0 -0
@@ -189,3 +189,7 @@ cython_debug/
189
189
  # pixi environments
190
190
  .pixi/*
191
191
  !.pixi/config.toml
192
+
193
+ # Local Claude and Codegraph data
194
+ .claude/
195
+ .codegraph/
@@ -6,26 +6,26 @@ existing import statements need no changes. When migrating an existing project,
6
6
  replace the old dependency rather than declaring both distributions, which
7
7
  provide the same Python packages.
8
8
 
9
- This checkout prepares 3.5.2 with the CI/CSF processing interfaces on the
10
- Python 3.15 / Polars 2.1 compatibility baseline.
9
+ This checkout prepares 3.6.0 with regression coverage for rCSFs V3 coupling
10
+ signatures and their alignment with GRASP mixing blocks.
11
11
  Use this source checkout until publication; the pinned PyPI examples below
12
- apply after 3.5.2 is available on the package index.
12
+ apply after 3.6.0 is available on the package index.
13
13
 
14
14
  ## Install from PyPI
15
15
 
16
- ```bash
16
+ ```fish
17
17
  python -m pip install graspkit-atomic
18
18
  ```
19
19
 
20
20
  For a fixed release:
21
21
 
22
- ```bash
23
- python -m pip install "graspkit-atomic==3.5.2"
22
+ ```fish
23
+ python -m pip install "graspkit-atomic==3.6.0"
24
24
  ```
25
25
 
26
26
  ## Declare a project dependency
27
27
 
28
- Add `"graspkit-atomic==3.5.2"` to the existing `[project].dependencies` list in
28
+ Add `"graspkit-atomic==3.6.0"` to the existing `[project].dependencies` list in
29
29
  your own `pyproject.toml`. A minimal example:
30
30
 
31
31
  ```toml
@@ -33,7 +33,7 @@ your own `pyproject.toml`. A minimal example:
33
33
  name = "atomic-analysis"
34
34
  version = "0.1.0"
35
35
  requires-python = ">=3.15"
36
- dependencies = ["graspkit-atomic==3.5.2"]
36
+ dependencies = ["graspkit-atomic==3.6.0"]
37
37
  ```
38
38
 
39
39
  For a uv-managed project, run `uv sync` after editing `pyproject.toml`, then
@@ -41,7 +41,7 @@ For a uv-managed project, run `uv sync` after editing `pyproject.toml`, then
41
41
  add the dependency and update the lockfile/environment in one step, use
42
42
  `uv add graspkit-atomic`. See the [README](README.md#with-uv) for a new-project
43
43
  example. Alternatively, install a pip-managed project with `python -m pip install .`.
44
- Add `"rcsfs==1.3.1"` separately if your application also needs the Rust CSF library.
44
+ Install a V3-capable rCSFs build separately to read V3 descriptors.
45
45
 
46
46
  Pip installs the declared runtime dependencies; Rust and the GRASP executables
47
47
  are not needed to install this Python library. Reading calculation results
@@ -51,15 +51,15 @@ requires the corresponding GRASP data files.
51
51
 
52
52
  To install a downloaded wheel, use its exact filename:
53
53
 
54
- ```bash
55
- python -m pip install /path/to/graspkit_atomic-3.5.2-py3-none-any.whl
54
+ ```fish
55
+ python -m pip install /path/to/graspkit_atomic-3.6.0-py3-none-any.whl
56
56
  ```
57
57
 
58
58
  A standalone source checkout also supports `python -m pip install .`.
59
59
 
60
60
  ## Verification
61
61
 
62
- ```bash
62
+ ```fish
63
63
  python -c "from graspkit.data_IO import EnergyFileLoader; print(EnergyFileLoader)"
64
64
  python -c "import graspkit_plot; print(graspkit_plot.__file__)"
65
65
  ```
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: graspkit-atomic
3
- Version: 3.5.2
3
+ Version: 3.6.0
4
4
  Summary: Stable data I/O, processing, and plotting for GRASP calculations
5
5
  Project-URL: Homepage, https://github.com/YenochQin/graspkit
6
6
  Project-URL: Source, https://github.com/YenochQin/graspkit
@@ -63,14 +63,13 @@ GRASP atomic-structure calculation results.
63
63
  quantum-number helpers.
64
64
  - `graspkit_plot`: plotting and publication-style helpers.
65
65
 
66
- For version 3.5.2's cumulative CI² selection, index mapping and
67
- orbital coverage interfaces, see [CSF processing primitives](docs/csf-selection-primitives.md).
68
- These newly added interfaces require this source checkout until the next release.
66
+ Version 3.6.0 verifies coupling-channel selection against rCSFs V3 descriptors
67
+ and GRASP mixing blocks. See the [release notes](docs/releasing.md#changes-in-360)
68
+ and the [CSF processing primitives](docs/csf-selection-primitives.md).
69
69
 
70
70
  ## Installation
71
71
 
72
- The Python 3.15 / Polars 2.1 compatibility changes are unreleased; use this
73
- source checkout until the next package release.
72
+ Use this source checkout for 3.6.0 until the package is published.
74
73
 
75
74
  Install [graspkit-atomic from PyPI](https://pypi.org/project/graspkit-atomic/)
76
75
  with Python 3.15 or newer. The distribution name is `graspkit-atomic`;
@@ -81,7 +80,7 @@ its Python import packages are `graspkit` and `graspkit_plot`.
81
80
  Use [uv](https://docs.astral.sh/uv/getting-started/installation/) to manage the
82
81
  environment and dependencies of your own analysis project. For a new project:
83
82
 
84
- ```bash
83
+ ```fish
85
84
  uv init --python 3.15 atomic-analysis
86
85
  cd atomic-analysis
87
86
  uv add graspkit-atomic
@@ -92,7 +91,7 @@ For an existing uv project using Python 3.15 or newer, run `uv add graspkit-atom
92
91
  in its directory. This records the dependency in `pyproject.toml`, updates
93
92
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
94
93
  to run your own analysis script; manual environment activation is not required.
95
- To pin a particular release, use `uv add "graspkit-atomic==3.5.2"`.
94
+ After 3.6.0 is available on the package index, pin it with `uv add "graspkit-atomic==3.6.0"`.
96
95
 
97
96
  You can also add the dependency to an existing `pyproject.toml` manually:
98
97
 
@@ -102,7 +101,7 @@ name = "atomic-analysis"
102
101
  version = "0.1.0"
103
102
  requires-python = ">=3.15"
104
103
  dependencies = [
105
- "graspkit-atomic==3.5.2",
104
+ "graspkit-atomic==3.6.0",
106
105
  ]
107
106
  ```
108
107
 
@@ -114,7 +113,7 @@ your analysis code to record the dependency choices.
114
113
 
115
114
  To install into an existing Python environment:
116
115
 
117
- ```bash
116
+ ```fish
118
117
  python -m pip install graspkit-atomic
119
118
  ```
120
119
 
@@ -16,14 +16,13 @@ GRASP atomic-structure calculation results.
16
16
  quantum-number helpers.
17
17
  - `graspkit_plot`: plotting and publication-style helpers.
18
18
 
19
- For version 3.5.2's cumulative CI² selection, index mapping and
20
- orbital coverage interfaces, see [CSF processing primitives](docs/csf-selection-primitives.md).
21
- These newly added interfaces require this source checkout until the next release.
19
+ Version 3.6.0 verifies coupling-channel selection against rCSFs V3 descriptors
20
+ and GRASP mixing blocks. See the [release notes](docs/releasing.md#changes-in-360)
21
+ and the [CSF processing primitives](docs/csf-selection-primitives.md).
22
22
 
23
23
  ## Installation
24
24
 
25
- The Python 3.15 / Polars 2.1 compatibility changes are unreleased; use this
26
- source checkout until the next package release.
25
+ Use this source checkout for 3.6.0 until the package is published.
27
26
 
28
27
  Install [graspkit-atomic from PyPI](https://pypi.org/project/graspkit-atomic/)
29
28
  with Python 3.15 or newer. The distribution name is `graspkit-atomic`;
@@ -34,7 +33,7 @@ its Python import packages are `graspkit` and `graspkit_plot`.
34
33
  Use [uv](https://docs.astral.sh/uv/getting-started/installation/) to manage the
35
34
  environment and dependencies of your own analysis project. For a new project:
36
35
 
37
- ```bash
36
+ ```fish
38
37
  uv init --python 3.15 atomic-analysis
39
38
  cd atomic-analysis
40
39
  uv add graspkit-atomic
@@ -45,7 +44,7 @@ For an existing uv project using Python 3.15 or newer, run `uv add graspkit-atom
45
44
  in its directory. This records the dependency in `pyproject.toml`, updates
46
45
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
47
46
  to run your own analysis script; manual environment activation is not required.
48
- To pin a particular release, use `uv add "graspkit-atomic==3.5.2"`.
47
+ After 3.6.0 is available on the package index, pin it with `uv add "graspkit-atomic==3.6.0"`.
49
48
 
50
49
  You can also add the dependency to an existing `pyproject.toml` manually:
51
50
 
@@ -55,7 +54,7 @@ name = "atomic-analysis"
55
54
  version = "0.1.0"
56
55
  requires-python = ">=3.15"
57
56
  dependencies = [
58
- "graspkit-atomic==3.5.2",
57
+ "graspkit-atomic==3.6.0",
59
58
  ]
60
59
  ```
61
60
 
@@ -67,7 +66,7 @@ your analysis code to record the dependency choices.
67
66
 
68
67
  To install into an existing Python environment:
69
68
 
70
- ```bash
69
+ ```fish
71
70
  python -m pip install graspkit-atomic
72
71
  ```
73
72
 
@@ -12,12 +12,12 @@
12
12
  - `graspkit.utils`:通用 GRASP 数据模型、环境检测和量子数工具。
13
13
  - `graspkit_plot`:绘图和出版级样式工具。
14
14
 
15
- 3.5.2 的 CI² 累计筛选、索引映射与轨道覆盖接口见
16
- [CSF 处理接口文档](docs/csf-selection-primitives.md)。这些新增接口尚未发布,需使用配套源码。
15
+ 3.6.0 验证了使用 rCSFs V3 描述符与 GRASP 混合系数分块进行耦合通道筛选的流程。
16
+ 详见[版本说明](docs/releasing.md#changes-in-360)和 [CSF 处理接口文档](docs/csf-selection-primitives.md)。
17
17
 
18
18
  ## 安装
19
19
 
20
- Python 3.15 / Polars 2.1 兼容修改尚未发布,请暂用源码版本。
20
+ 3.6.0 发布前可使用本版源码安装。
21
21
 
22
22
  使用 Python 3.15 或更新版本,从 [PyPI 安装 graspkit-atomic](https://pypi.org/project/graspkit-atomic/)。
23
23
  分发包名为 `graspkit-atomic`,Python 导入名为 `graspkit` 和 `graspkit_plot`。
@@ -26,7 +26,7 @@ Python 3.15 / Polars 2.1 兼容修改尚未发布,请暂用源码版本。
26
26
 
27
27
  可以用 [uv](https://docs.astral.sh/uv/getting-started/installation/) 管理你自己的分析项目环境和依赖。新建项目时:
28
28
 
29
- ```bash
29
+ ```fish
30
30
  uv init --python 3.15 atomic-analysis
31
31
  cd atomic-analysis
32
32
  uv add graspkit-atomic
@@ -36,7 +36,7 @@ uv run python -c "import graspkit; print(graspkit.__version__)"
36
36
  已有 uv 项目使用 Python 3.15 或更新版本时,直接在其目录运行 `uv add graspkit-atomic`。
37
37
  该命令会将依赖写入 `pyproject.toml`,更新 `uv.lock`,并安装到项目的 `.venv` 中。
38
38
  运行自己的分析脚本时使用 `uv run python analysis.py`,无需手动激活环境。
39
- 需要固定版本时,使用 `uv add "graspkit-atomic==3.5.2"`。
39
+ 3.6.0 在包索引可用后,可用 `uv add "graspkit-atomic==3.6.0"` 固定版本。
40
40
 
41
41
  也可以手动将依赖加入已有的 `pyproject.toml`:
42
42
 
@@ -46,7 +46,7 @@ name = "atomic-analysis"
46
46
  version = "0.1.0"
47
47
  requires-python = ">=3.15"
48
48
  dependencies = [
49
- "graspkit-atomic==3.5.2",
49
+ "graspkit-atomic==3.6.0",
50
50
  ]
51
51
  ```
52
52
 
@@ -57,7 +57,7 @@ dependencies = [
57
57
 
58
58
  安装到已有的 Python 环境:
59
59
 
60
- ```bash
60
+ ```fish
61
61
  python -m pip install graspkit-atomic
62
62
  ```
63
63
 
@@ -1,11 +1,11 @@
1
1
  # CI weights, CSF indices and orbital coverage
2
2
 
3
- Available in the prepared GraspKit 3.5.2 source version.
3
+ This guide describes GraspKit 3.6.0.
4
4
 
5
5
  The public functions below belong to `graspkit.CSFs_processor`. They do not
6
6
  depend on ML configuration, PyTorch, scikit-learn or a calculation workflow.
7
7
  Callers choose thresholds and budgets and decide what to do with the returned
8
- diagnostics. Descriptor generation and the V2 format remain owned by rCSFs.
8
+ diagnostics. rCSFs owns descriptor generation and the V3 Parquet format.
9
9
 
10
10
  ## Cumulative selection
11
11
 
@@ -51,6 +51,35 @@ block offsets. It uses relative normalization and importance traversal order.
51
51
  The existing `rmix_cumulative_selected_row_idxs(RmixCiSquaredData, ...)` delegates
52
52
  to this block interface; its loader has already selected the requested ASF rows.
53
53
 
54
+ ## Coupling groups
55
+
56
+ Read the descriptor dataset with a V3-capable rCSFs build using
57
+ `rcsfs.read_csfs(path, include_block_id=True, include_coupling_signature=True)`.
58
+ Pass the returned DataFrame to `collect_coupling_groups`,
59
+ `summarize_coupling_ci_squared`, or the coupling selection functions.
60
+ rCSFs validates the file version and layout.
61
+
62
+ - `idx` is the original CSF row number. `block_id` identifies each explicit
63
+ block, including adjacent blocks with the same J and parity.
64
+ - `coupling_signature` is a non-empty Polars `List(Int32)` of doubled angular
65
+ momenta derived from the canonical print positions of occupied peel
66
+ subshells. Zeros at intermediate positions are valid. The last entry is
67
+ physical total `2J`, so a J = 1/2 CSF has signature tail `1` and stored
68
+ `total_two_j_plus_one` of `2`. A pure closed-core CSF has signature `[0]`.
69
+ The V3 raw cumulative `2K+1` codes describe coupling through every peel
70
+ position, including empty and closed subshells.
71
+ - A specified `coupling_level` counts trailing entries after removing total
72
+ `2J`. For example, at depth 1, `[0, 1, 0, 1]` and `[0, 1, 2, 1]`
73
+ give groups `[0]` and `[2]`. With `None`, the complete signature is used.
74
+ - Group members have zero-based block-local positions in `idxs` and original
75
+ row numbers in `global_idxs`. Weighting and selection match the explicit
76
+ block order, verify the signature's total `2J` and the number of coefficient
77
+ columns, and use block-local positions to index the mixing matrices. The
78
+ selected rows retain their original `idx`.
79
+
80
+ The [V3 coupling plan](csf-descriptor-v3-coupling-plan.md) records the
81
+ block-alignment cases and the fixture-based regression command.
82
+
54
83
  ## Indices
55
84
 
56
85
  - `validate_selection_idxs` checks one-dimensional integer indices, bounds,
@@ -1,11 +1,24 @@
1
1
  # Preparing a graspkit-atomic release
2
2
 
3
- The prepared stable version is **3.5.2**. Its single source is
3
+ The prepared version is **3.6.0**. Its single source is
4
4
  `src/graspkit/version.py`; Hatchling reads it through `dynamic = ["version"]`.
5
- Version 3.5.2 adds the CI/CSF processing interfaces on the 3.5.1 compatibility baseline; publication is a separate step.
6
5
  The local build commands below do not upload files or create Git tags.
7
6
  The separate manual publishing workflow is described near the end of this guide.
8
7
 
8
+ ## Changes in 3.6.0
9
+
10
+ - Verify coupling grouping and CI² selection from rCSFs V3 descriptors against
11
+ GRASP mixing blocks. The regression covers explicit block identity, original
12
+ CSF ordinals and physical total `2J` in the derived coupling signatures.
13
+ - Document the V3 coupling contract and the fixture-based regression command.
14
+
15
+ ## Changes in 3.5.3
16
+
17
+ - `select_csfs_by_cumulative_coupling` takes the union of each selected ASF's
18
+ cumulative CI² prefix and the CSFs in its dominant coupling channel.
19
+ - `save_mid_coupling_plots` groups CSFs once and writes a plot for each requested
20
+ ASF in SVG, PNG, or PDF format.
21
+
9
22
  ## Changes in 3.5.2
10
23
 
11
24
  - Provide deterministic per-ASF cumulative CI-squared selection and diagnostics.
@@ -41,8 +54,8 @@ The separate manual publishing workflow is described near the end of this guide.
41
54
  Set up or refresh the shared environment from `graspkit-tools/` with
42
55
  `uv sync --extra cpu` (`--extra gpu` on a CUDA host). Then, from `graspkit/`:
43
56
 
44
- ```bash
45
- source ../graspkit-tools/.venv/bin/activate
57
+ ```fish
58
+ source ../graspkit-tools/.venv/bin/activate.fish
46
59
  python build_package.py --clean
47
60
  ```
48
61
 
@@ -54,13 +67,13 @@ The obsolete `--dev` option is removed; edit the version source deliberately.
54
67
  `--clean` removes only matching graspkit-atomic archives from the selected output
55
68
  folder. Unknown files cause an error instead of being deleted.
56
69
 
57
- Output: `dist/graspkit_atomic-3.5.2.tar.gz` and
58
- `dist/graspkit_atomic-3.5.2-py3-none-any.whl`. An optional `--outdir PATH` selects an
70
+ Output files are `dist/graspkit_atomic-3.6.0.tar.gz` and
71
+ `dist/graspkit_atomic-3.6.0-py3-none-any.whl`. An optional `--outdir PATH` selects an
59
72
  empty output folder. The shell/batch wrappers select the shared Tools Python.
60
73
 
61
74
  Equivalent individual checks:
62
75
 
63
- ```bash
76
+ ```fish
64
77
  python -m build
65
78
  python -m twine check --strict dist/*
66
79
  python scripts/check_release.py dist --smoke
@@ -99,7 +112,7 @@ Python versions above 3.15 are permitted by metadata but not yet in this matrix.
99
112
  Until the workflow reaches the default branch, start a check from the release
100
113
  commit by pushing it to a dedicated branch, for example:
101
114
 
102
- ```bash
115
+ ```fish
103
116
  git push origin HEAD:refs/heads/codex/release-build-check-20261020
104
117
  ```
105
118
 
@@ -111,7 +124,7 @@ with a branch selector. Review all three platform jobs before using the artifact
111
124
  ## Before a later publication
112
125
 
113
126
  1. Review the exact source commit and release changes; rerun the workflow on it.
114
- 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.5.2
127
+ 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.6.0
115
128
  has not already been published. A missing public project page alone does
116
129
  not prove that a name is available.
117
130
  3. Inspect the actual archives and hashes. Publishing makes their contents
@@ -135,7 +148,7 @@ completing a build does not start a publication. Its inputs are:
135
148
 
136
149
  | Input | Default | Purpose |
137
150
  | --- | --- | --- |
138
- | `version` | Required | Exact source version, currently `3.5.2`. |
151
+ | `version` | Required | Exact source version, currently `3.6.0`. |
139
152
  | `publish_pypi` | Off | Upload the validated packages to PyPI. |
140
153
  | `github_release` | Off | Create a GitHub Release using the same packages. |
141
154
  | `draft` | On | Keep the GitHub Release as a draft; turn off only for formal publication. |
@@ -151,7 +164,7 @@ source version, and select the destinations you intend to use:
151
164
  | On | On | Build and validate once, then upload the same files to both destinations. |
152
165
 
153
166
  A prior dry run is optional. No separate workflow, run ID or tag input is
154
- needed. The GitHub tag is derived as `v{version}`, for example `v3.5.2`.
167
+ needed. The GitHub tag is derived as `v{version}`, for example `v3.6.0`.
155
168
  The `draft` option has no effect when `github_release` is off.
156
169
 
157
170
  ### One build, two independent destinations
@@ -2,7 +2,9 @@
2
2
  """CSF parsing, coupling-J analysis, and deterministic selection algorithms."""
3
3
 
4
4
  from .coupling import (
5
+ CumulativeCouplingSelection,
5
6
  collect_coupling_groups,
7
+ select_csfs_by_cumulative_coupling,
6
8
  select_csfs_by_coupling_theme,
7
9
  summarize_coupling_ci_squared,
8
10
  )
@@ -41,7 +43,9 @@ from .validation import (
41
43
 
42
44
  __all__ = [
43
45
  # coupling
46
+ "CumulativeCouplingSelection",
44
47
  "collect_coupling_groups",
48
+ "select_csfs_by_cumulative_coupling",
45
49
  "select_csfs_by_coupling_theme",
46
50
  "summarize_coupling_ci_squared",
47
51
  # selection
@@ -1,8 +1,23 @@
1
1
  # -*- encoding: utf-8 -*-
2
- """Polars coupling-signature analysis for rCSFs DataFrames."""
2
+ """Analyze coupling signatures from the rCSFs V3 DataFrame interface.
3
+
4
+ Use ``rcsfs.read_csfs`` with ``include_block_id`` and
5
+ ``include_coupling_signature`` enabled. The reader supplies a non-empty
6
+ ``List(Int32)`` signature from the canonical print positions of occupied peel
7
+ subshells. Its intermediate entries are doubled angular momenta (including
8
+ valid zeros), and its final entry is the physical total ``2J``. A pure
9
+ closed-core CSF has signature ``[0]``. The V3 raw ``2J+1`` and ``2K+1`` codes
10
+ are separate columns interpreted by rCSFs.
11
+
12
+ ``block_id`` identifies the explicit source block, including adjacent blocks
13
+ with the same symmetry. Mixing coefficients use positions within each block.
14
+ ``idx`` records the original CSF row and is preserved in selections.
15
+ """
3
16
 
4
17
  from __future__ import annotations
5
18
 
19
+ from collections.abc import Iterator
20
+ from dataclasses import dataclass
6
21
  from fractions import Fraction
7
22
 
8
23
  import numpy as np
@@ -10,6 +25,7 @@ from numpy.typing import NDArray
10
25
  import polars as pl
11
26
 
12
27
  from ..utils.data_modules import MixCoefficientData
28
+ from .selection import select_csf_indices_by_cumulative_weight
13
29
  from .validation import (
14
30
  normalize_asf_row_indices,
15
31
  validate_coupling_level,
@@ -85,12 +101,11 @@ def collect_coupling_groups(
85
101
  """Group rCSFs coupling signatures with local and global CSF indices.
86
102
 
87
103
  Args:
88
- csfs_df: DataFrame returned by ``rcsfs.read_csfs`` with both
104
+ csfs_df: V3 DataFrame returned by ``rcsfs.read_csfs`` with both
89
105
  ``include_block_id`` and ``include_coupling_signature`` enabled.
90
- coupling_level: Number of trailing intermediate-coupling ``2J`` values
91
- used as the grouping pattern. The signature's final total J value
92
- is excluded before counting. ``None`` retains the complete
93
- signature, including total J.
106
+ coupling_level: Number of trailing intermediate entries used as the
107
+ grouping pattern. First remove the signature's final total ``2J``.
108
+ ``None`` retains the complete signature, including total ``2J``.
94
109
 
95
110
  Returns:
96
111
  One row per block and coupling pattern with columns ``block_id``,
@@ -129,11 +144,14 @@ def _selected_block_coefficients(
129
144
  csfs_df: pl.DataFrame,
130
145
  asfs_mix_data: MixCoefficientData,
131
146
  asf_row_indices: list[list[int]] | None,
132
- ) -> list[tuple[int, list[int], NDArray[np.float64]]]:
147
+ *,
148
+ allow_empty_blocks: bool = False,
149
+ ) -> Iterator[tuple[int, list[int], NDArray[np.float64]]]:
133
150
  """Validate J/CSF alignment and return selected ASF coefficient matrices."""
134
151
  normalized_positions = normalize_asf_row_indices(
135
152
  asfs_mix_data,
136
153
  asf_row_indices,
154
+ allow_empty_blocks=allow_empty_blocks,
137
155
  )
138
156
  dataframe_block_ids = (
139
157
  csfs_df.get_column("block_id").unique(maintain_order=True).to_list()
@@ -144,7 +162,6 @@ def _selected_block_coefficients(
144
162
  f"CSF block IDs {dataframe_block_ids} 与 rmix block IDs {mix_block_ids} 不一致"
145
163
  )
146
164
 
147
- selected_blocks: list[tuple[int, list[int], NDArray[np.float64]]] = []
148
165
  for mix_block, mix_j_value, selected_positions in zip(
149
166
  asfs_mix_data.blocks,
150
167
  asfs_mix_data.level_J_value_list,
@@ -160,21 +177,16 @@ def _selected_block_coefficients(
160
177
  f"Block {mix_block.block_index}: mixing coefficients 必须是二维矩阵"
161
178
  )
162
179
 
163
- dataframe_block = csfs_df.filter(
164
- pl.col("block_id") == mix_block.block_index
180
+ signatures = csfs_df[_COUPLING_SIGNATURE_COLUMN].filter(
181
+ csfs_df["block_id"] == mix_block.block_index
165
182
  )
166
- dataframe_csf_count = dataframe_block.height
183
+ dataframe_csf_count = len(signatures)
167
184
  if coefficient_matrix.shape[1] != dataframe_csf_count:
168
185
  raise ValueError(
169
186
  f"Block {mix_block.block_index}: rmix CSF 数量 {coefficient_matrix.shape[1]} 与 CSF DataFrame {dataframe_csf_count} 不一致"
170
187
  )
171
188
 
172
- csf_two_j_values = (
173
- dataframe_block.get_column(_COUPLING_SIGNATURE_COLUMN)
174
- .list.last()
175
- .unique(maintain_order=True)
176
- .to_list()
177
- )
189
+ csf_two_j_values = signatures.list.last().unique(maintain_order=True).to_list()
178
190
  if len(csf_two_j_values) != 1:
179
191
  raise ValueError(
180
192
  f"Block {mix_block.block_index}: CSF DataFrame 包含多个总 J: 2J={csf_two_j_values}"
@@ -186,14 +198,11 @@ def _selected_block_coefficients(
186
198
  f"Block {mix_block.block_index}: CSF J={_format_twice_j(csf_two_j)} 与 rmix J={mix_j_value} 不一致"
187
199
  )
188
200
 
189
- selected_blocks.append(
190
- (
191
- mix_block.block_index,
192
- selected_positions,
193
- coefficient_matrix[selected_positions],
194
- )
201
+ yield (
202
+ mix_block.block_index,
203
+ selected_positions,
204
+ coefficient_matrix[selected_positions],
195
205
  )
196
- return selected_blocks
197
206
 
198
207
 
199
208
  def _twice_j_value(j_value: str, *, block_index: int) -> int:
@@ -216,53 +225,38 @@ def _format_twice_j(two_j: int) -> str:
216
225
  return f"{two_j}/2"
217
226
 
218
227
 
219
- def _mixing_coefficients_to_long_frame(
228
+ @dataclass(frozen=True)
229
+ class _WeightedCouplingBlock:
230
+ block_id: int
231
+ asf_rows: list[int]
232
+ groups: pl.DataFrame
233
+ ci_squared: NDArray[np.float64]
234
+ channel_sums: NDArray[np.float64]
235
+
236
+
237
+ def _weighted_coupling_blocks(
220
238
  csfs_df: pl.DataFrame,
221
- asfs_mix_data: MixCoefficientData,
239
+ mix_data: MixCoefficientData,
222
240
  asf_row_indices: list[list[int]] | None,
223
- ) -> pl.DataFrame:
224
- """Convert selected ASF-by-CSF matrices to one Polars long frame."""
225
- long_frames: list[pl.DataFrame] = []
226
- for (
227
- block_index,
228
- selected_positions,
229
- selected_coefficients,
230
- ) in _selected_block_coefficients(csfs_df, asfs_mix_data, asf_row_indices):
231
- selected_count = len(selected_positions)
232
- csf_count = selected_coefficients.shape[1]
233
- long_frames.append(
234
- pl.DataFrame(
235
- {
236
- "block_id": np.full(
237
- selected_count * csf_count,
238
- block_index,
239
- dtype=np.uint32,
240
- ),
241
- "asf_index": np.repeat(
242
- np.asarray(selected_positions, dtype=np.int64),
243
- csf_count,
244
- ),
245
- "block_csf_idx": np.tile(
246
- np.arange(csf_count, dtype=np.uint64),
247
- selected_count,
248
- ),
249
- "ci_squared": np.square(
250
- selected_coefficients,
251
- dtype=np.float64,
252
- ).reshape(-1),
253
- },
254
- schema={
255
- "block_id": pl.UInt32,
256
- "asf_index": pl.Int64,
257
- "block_csf_idx": pl.UInt64,
258
- "ci_squared": pl.Float64,
259
- },
260
- )
261
- )
262
-
263
- if not long_frames:
264
- raise ValueError("没有可汇总的 mixing coefficient block")
265
- return pl.concat(long_frames, how="vertical")
241
+ coupling_level: int | None,
242
+ *,
243
+ allow_empty_blocks: bool = False,
244
+ ) -> Iterator[_WeightedCouplingBlock]:
245
+ """Group each CSF once, then sum each ASF over the same source-ordered members."""
246
+ groups = collect_coupling_groups(csfs_df, coupling_level)
247
+ for block_id, rows, coefficients in _selected_block_coefficients(
248
+ csfs_df, mix_data, asf_row_indices, allow_empty_blocks=allow_empty_blocks
249
+ ):
250
+ if not rows:
251
+ continue
252
+ block_groups = groups.filter(pl.col("block_id") == block_id)
253
+ members = block_groups["idxs"].explode().to_numpy()
254
+ counts = block_groups["count"].to_numpy()
255
+ starts = np.cumsum(counts, dtype=np.int64) - counts
256
+ weights = np.square(coefficients)
257
+ # Reduce one ASF at a time to bound temporary storage by the block size.
258
+ sums = np.stack([np.add.reduceat(row[members], starts) for row in weights])
259
+ yield _WeightedCouplingBlock(block_id, rows, block_groups, weights, sums)
266
260
 
267
261
 
268
262
  def summarize_coupling_ci_squared(
@@ -270,56 +264,103 @@ def summarize_coupling_ci_squared(
270
264
  asfs_mix_data: MixCoefficientData,
271
265
  asf_row_indices: list[list[int]] | None = None,
272
266
  coupling_level: int | None = None,
267
+ *,
268
+ include_members: bool = True,
269
+ allow_empty_blocks: bool = False,
273
270
  ) -> pl.DataFrame:
274
- """Summarize CI-square contributions by block, ASF, and coupling pattern.
271
+ """Return channel counts and CI² sums in block, ASF and source-channel order.
275
272
 
276
- The returned frame is in long form: one row represents one selected ASF
277
- and one coupling signature in one block. This keeps the ASF identity
278
- explicit instead of encoding aligned sums in nested dictionaries.
273
+ By default also return the block-local and source indices of each member.
274
+ For plots, omit the member lists and allow empty ASF lists to skip blocks.
279
275
  """
280
- _validate_coupling_frame(csfs_df)
281
- annotated = _with_selected_coupling(csfs_df, coupling_level).select(
282
- "block_id",
283
- "block_csf_idx",
284
- pl.col("idx").cast(pl.UInt64()),
285
- _SELECTED_COUPLING_COLUMN,
286
- )
287
- coefficient_frame = _mixing_coefficients_to_long_frame(
276
+ frames: list[pl.DataFrame] = []
277
+ for block in _weighted_coupling_blocks(
288
278
  csfs_df,
289
279
  asfs_mix_data,
290
280
  asf_row_indices,
291
- )
292
- joined = coefficient_frame.join(
293
- annotated,
294
- on=["block_id", "block_csf_idx"],
295
- how="inner",
296
- validate="m:1",
297
- maintain_order="left",
298
- )
299
- if joined.height != coefficient_frame.height:
300
- raise ValueError("mixing coefficient 行与 CSF DataFrame 未能完整对齐")
281
+ coupling_level,
282
+ allow_empty_blocks=allow_empty_blocks,
283
+ ):
284
+ groups = (
285
+ block.groups
286
+ if include_members
287
+ else block.groups.drop("idxs", "global_idxs")
288
+ )
289
+ for asf_index, channel_sums in zip(
290
+ block.asf_rows, block.channel_sums, strict=True
291
+ ):
292
+ frames.append(
293
+ groups.with_columns(
294
+ pl.lit(asf_index, dtype=pl.Int64).alias("asf_index"),
295
+ pl.Series("sum_ci", channel_sums),
296
+ )
297
+ )
298
+ schema: dict[str, type[pl.DataType] | pl.DataType] = {
299
+ "block_id": pl.UInt32,
300
+ "asf_index": pl.Int64,
301
+ "coupling_signature": pl.List(pl.Int32),
302
+ "count": pl.UInt32,
303
+ }
304
+ if include_members:
305
+ schema.update(idxs=pl.List(pl.UInt64), global_idxs=pl.List(pl.UInt64))
306
+ schema["sum_ci"] = pl.Float64
307
+ if not frames:
308
+ return pl.DataFrame(schema=schema)
309
+ return pl.concat(frames).select(list(schema)).cast({"block_id": pl.UInt32})
310
+
311
+
312
+ @dataclass(frozen=True)
313
+ class CumulativeCouplingSelection:
314
+ """Source-ordered selection and the statistics used to construct it."""
315
+
316
+ selected_csfs: pl.DataFrame
317
+ prefix_counts: dict[int, int]
318
+ dominant_channels: pl.DataFrame
319
+
320
+
321
+ def select_csfs_by_cumulative_coupling(
322
+ csfs_df: pl.DataFrame,
323
+ mix_data: MixCoefficientData,
324
+ *,
325
+ cumulative_threshold: float,
326
+ coupling_level: int,
327
+ asf_row_indices: list[list[int]] | None = None,
328
+ ) -> CumulativeCouplingSelection:
329
+ """Union each selected ASF's normalized CI² prefix and its dominant channel.
301
330
 
302
- return (
303
- joined.group_by(
304
- ["block_id", "asf_index", _SELECTED_COUPLING_COLUMN],
305
- maintain_order=True,
331
+ Prefix ties follow select_csf_indices_by_cumulative_weight. Equal channel
332
+ sums select the first channel in CSF source order, as in ML presampling.
333
+ """
334
+ selected = np.zeros(csfs_df.height, dtype=np.bool_)
335
+ prefix_counts: dict[int, int] = {}
336
+ dominant_frames: list[pl.DataFrame] = []
337
+ for block in _weighted_coupling_blocks(
338
+ csfs_df, mix_data, asf_row_indices, coupling_level
339
+ ):
340
+ prefix = select_csf_indices_by_cumulative_weight(
341
+ block.ci_squared, cumulative_threshold=cumulative_threshold
306
342
  )
307
- .agg(
308
- pl.len().alias("count"),
309
- pl.col("block_csf_idx").alias("idxs"),
310
- pl.col("idx").alias("global_idxs"),
311
- pl.col("ci_squared").sum().alias("sum_ci"),
343
+ prefix_counts[block.block_id] = len(prefix.indices)
344
+ winners = np.argmax(block.channel_sums, axis=1)
345
+ block_mask = np.zeros(block.ci_squared.shape[1], dtype=np.bool_)
346
+ block_mask[prefix.indices] = True
347
+ theme_members = (
348
+ block.groups["idxs"].gather(np.unique(winners)).explode().to_numpy()
312
349
  )
313
- .rename({_SELECTED_COUPLING_COLUMN: _COUPLING_SIGNATURE_COLUMN})
314
- .select(
315
- "block_id",
316
- "asf_index",
317
- _COUPLING_SIGNATURE_COLUMN,
318
- "count",
319
- "idxs",
320
- "global_idxs",
321
- "sum_ci",
350
+ block_mask[theme_members] = True
351
+ selected[csfs_df["block_id"].to_numpy() == block.block_id] = block_mask
352
+ dominant_frames.append(
353
+ block.groups.select("block_id", "coupling_signature", "count")[
354
+ winners
355
+ ].with_columns(
356
+ pl.Series("asf_index", block.asf_rows, dtype=pl.Int64),
357
+ pl.Series(
358
+ "sum_ci", block.channel_sums[np.arange(len(winners)), winners]
359
+ ),
360
+ )
322
361
  )
362
+ return CumulativeCouplingSelection(
363
+ csfs_df.filter(selected), prefix_counts, pl.concat(dominant_frames)
323
364
  )
324
365
 
325
366
 
@@ -333,15 +374,14 @@ def select_csfs_by_coupling_theme(
333
374
  ) -> pl.DataFrame:
334
375
  """Select rCSFs rows by CI-square threshold and dominant coupling theme.
335
376
 
336
- The input must be returned by :func:`rcsfs.read_csfs` with both
377
+ The V3 input must be returned by :func:`rcsfs.read_csfs` with both
337
378
  ``include_block_id`` and ``include_coupling_signature`` enabled. For every
338
379
  block, the result is the source-ordered union of CSFs whose selected-ASF
339
380
  CI-square exceeds ``ci_squared_cutoff`` and every member of the dominant coupling
340
381
  group for each selected ASF.
341
382
 
342
- ``coupling_level`` is the positive number of trailing intermediate-coupling
343
- integer ``2J`` values retained from the rCSFs fixed-width coupling
344
- signature. The final total J value is excluded before counting.
383
+ ``coupling_level`` counts trailing intermediate entries after removing
384
+ the final total ``2J``, as in :func:`collect_coupling_groups`.
345
385
  """
346
386
  validate_coupling_level(coupling_level)
347
387
  if type(ci_squared_cutoff) not in (int, float):
@@ -203,6 +203,8 @@ def validate_coupling_level(coupling_level: int | None) -> int | None:
203
203
  def normalize_asf_row_indices(
204
204
  asfs_mix_data: MixCoefficientData,
205
205
  asf_row_indices: Sequence[Sequence[int]] | None,
206
+ *,
207
+ allow_empty_blocks: bool = False,
206
208
  ) -> list[list[int]]:
207
209
  """Normalize and validate ASF matrix row indices for every rmix block."""
208
210
  if asf_row_indices is None:
@@ -221,7 +223,7 @@ def normalize_asf_row_indices(
221
223
  for block, row_indices in zip(
222
224
  asfs_mix_data.blocks, normalized_row_indices, strict=True
223
225
  ):
224
- if not row_indices:
226
+ if not row_indices and not allow_empty_blocks:
225
227
  raise ValueError(f"Block {block.block_index}: asf_row_indices 不能为空")
226
228
  if len(row_indices) != len(set(row_indices)):
227
229
  raise ValueError(f"Block {block.block_index}: asf_row_indices 包含重复值")
@@ -1,3 +1,3 @@
1
1
  """Package version, also read by Hatchling when building distributions."""
2
2
 
3
- __version__ = "3.5.2"
3
+ __version__ = "3.6.0"
@@ -43,6 +43,8 @@ __all__ = [
43
43
  "optimize_for_multi_subplot",
44
44
  "optimize_for_plot_type",
45
45
  "plot_mid_coupling_contribution",
46
+ "mid_coupling_output_stem",
47
+ "save_mid_coupling_plots",
46
48
  "resolve_transformed_xscale",
47
49
  "rwfn_plot",
48
50
  "rwfns_compare_plot",
@@ -57,6 +57,19 @@ def _coupling_label(signature: list[int]) -> str:
57
57
  return labels[0] if len(labels) == 1 else "(" + ", ".join(labels) + ")"
58
58
 
59
59
 
60
+ def _twice_j_value(j_value: str) -> int:
61
+ if "/" in j_value:
62
+ numerator, denominator = j_value.split("/", maxsplit=1)
63
+ return 2 * int(numerator) // int(denominator)
64
+ return 2 * int(j_value)
65
+
66
+
67
+ def mid_coupling_output_stem(*, parity: int, asf_row_index: int, j_value: str) -> str:
68
+ """Name a plot using parity, one-based ASF row and twice J."""
69
+ parity_prefix = {1: "e", 2: "o"}.get(parity, f"p{parity}")
70
+ return f"{parity_prefix}{asf_row_index + 1}_2J{_twice_j_value(j_value)}_MCJ"
71
+
72
+
60
73
  def _find_block(mix_data: MixCoefficientData, block_id: int) -> MixCoefficientBlock:
61
74
  for block in mix_data.blocks:
62
75
  if block.block_index == block_id:
@@ -76,35 +89,51 @@ def build_mid_coupling_plot_series(
76
89
  max_channels: int | None = None,
77
90
  ) -> MidCouplingPlotSeries:
78
91
  """Aggregate one ASF into contribution-sorted channels and an Others bin."""
79
- if not math.isfinite(min_csf_percentage) or min_csf_percentage < 0:
80
- raise ValueError("min_csf_percentage must be finite and non-negative")
81
- if not math.isfinite(min_contribution) or min_contribution < 0:
82
- raise ValueError("min_contribution must be finite and non-negative")
83
- if max_channels is not None and max_channels <= 0:
84
- raise ValueError("max_channels must be a positive integer or None")
85
-
86
92
  block = _find_block(mix_data, block_id)
87
93
  if asf_row_index < 0 or asf_row_index >= block.level_count:
88
94
  raise ValueError(
89
95
  f"block {block_id} asf_row_index is outside [0, {block.level_count})"
90
96
  )
91
-
92
97
  summary = summarize_coupling_ci_squared(
93
98
  csfs_df,
94
99
  mix_data,
95
100
  asf_row_indices=[
96
- [asf_row_index]
97
- if candidate.block_index == block_id
98
- else candidate.asf_row_indices.tolist()
101
+ [asf_row_index] if candidate.block_index == block_id else []
99
102
  for candidate in mix_data.blocks
100
103
  ],
101
104
  coupling_level=coupling_level,
102
- ).filter(
103
- (pl.col("block_id") == block_id)
104
- & (pl.col("asf_index") == asf_row_index)
105
+ include_members=False,
106
+ allow_empty_blocks=True,
107
+ )
108
+ return _series_from_summary(
109
+ summary,
110
+ block,
111
+ asf_row_index,
112
+ min_csf_percentage,
113
+ min_contribution,
114
+ max_channels,
105
115
  )
116
+
117
+
118
+ def _series_from_summary(
119
+ summary: pl.DataFrame,
120
+ block: MixCoefficientBlock,
121
+ asf_row_index: int,
122
+ min_csf_percentage: float,
123
+ min_contribution: float,
124
+ max_channels: int | None,
125
+ ) -> MidCouplingPlotSeries:
126
+ if not math.isfinite(min_csf_percentage) or min_csf_percentage < 0:
127
+ raise ValueError("min_csf_percentage must be finite and non-negative")
128
+ if not math.isfinite(min_contribution) or min_contribution < 0:
129
+ raise ValueError("min_contribution must be finite and non-negative")
130
+ if max_channels is not None and max_channels <= 0:
131
+ raise ValueError("max_channels must be a positive integer or None")
132
+
106
133
  if summary.is_empty():
107
- raise ValueError(f"block {block_id}, ASF row {asf_row_index} has no CSFs")
134
+ raise ValueError(
135
+ f"block {block.block_index}, ASF row {asf_row_index} has no CSFs"
136
+ )
108
137
 
109
138
  rows = sorted(
110
139
  summary.iter_rows(named=True),
@@ -138,7 +167,7 @@ def build_mid_coupling_plot_series(
138
167
 
139
168
  parity_labels = {1: "+", 2: "-"}
140
169
  return MidCouplingPlotSeries(
141
- block_id=block_id,
170
+ block_id=block.block_index,
142
171
  asf_row_index=asf_row_index,
143
172
  level_id=int(block.level_ids[asf_row_index]),
144
173
  j_value=block.j_value,
@@ -254,28 +283,32 @@ def plot_mid_coupling_contribution(
254
283
  alpha=0.75,
255
284
  label="Contribution Value",
256
285
  )
257
- contribution_axis.set_ylabel("Contribution Value", color=_TEXT_COLOR, fontsize=12)
286
+ contribution_axis.set_ylabel(
287
+ "Contribution Value", color=_TEXT_COLOR, fontsize=12
288
+ )
258
289
  contribution_axis.tick_params(axis="y", labelcolor=_TEXT_COLOR)
259
290
  contribution_upper_limit = _contribution_axis_upper_limit(series.contributions)
260
291
  contribution_axis.set_ylim(0.0, contribution_upper_limit)
261
292
 
262
293
  for index, bar in enumerate(bars):
263
294
  center = bar.get_x() + bar.get_width() / 2
264
- percentage_axis.annotate(
265
- f"{series.csf_percentages[index]:.1f}%",
266
- (center, bar.get_height()),
267
- xytext=(0, 4),
268
- textcoords="offset points",
269
- ha="center",
270
- va="bottom",
271
- )
295
+ layout = _contribution_label_layout(series.contributions, index)
272
296
  x_offset, y_offset, alignment = _avoid_bar_label_collision(
273
- layout=_contribution_label_layout(series.contributions, index),
297
+ layout=layout,
274
298
  contribution=series.contributions[index],
275
299
  contribution_upper_limit=contribution_upper_limit,
276
300
  csf_percentage=series.csf_percentages[index],
277
301
  percentage_upper_limit=percentage_upper_limit,
278
302
  )
303
+ separate_labels = y_offset > layout[1]
304
+ percentage_axis.annotate(
305
+ f"{series.csf_percentages[index]:.1f}%",
306
+ (center, bar.get_height()),
307
+ xytext=(8, 4) if separate_labels else (0, 4),
308
+ textcoords="offset points",
309
+ ha="left" if separate_labels else "center",
310
+ va="bottom",
311
+ )
279
312
  contribution_axis.annotate(
280
313
  f"{series.contributions[index]:.3f}",
281
314
  (x_positions[index], series.contributions[index]),
@@ -286,15 +319,71 @@ def plot_mid_coupling_contribution(
286
319
  color=_TEXT_COLOR,
287
320
  )
288
321
 
289
- contribution_axis.legend(loc="upper right", frameon=False)
322
+ contribution_axis.legend(loc="lower right", bbox_to_anchor=(1, 1), frameon=False)
290
323
  figure.tight_layout()
291
324
  figure.savefig(output_path, bbox_inches="tight")
292
325
  plt.close(figure)
293
326
  return output_path
294
327
 
295
328
 
329
+ def save_mid_coupling_plots(
330
+ csfs_df: pl.DataFrame,
331
+ mix_data: MixCoefficientData,
332
+ output_dir: Path,
333
+ *,
334
+ asf_row_indices: list[list[int]] | None = None,
335
+ coupling_level: int = 1,
336
+ min_csf_percentage: float = 0.0,
337
+ min_contribution: float = 0.0,
338
+ max_channels: int | None = None,
339
+ formats: tuple[str, ...] = ("svg",),
340
+ ) -> list[Path]:
341
+ """Group CSFs once and render each requested ASF in the specified formats."""
342
+ if not formats or any(fmt not in {"svg", "png", "pdf"} for fmt in formats):
343
+ raise ValueError("formats must contain svg, png or pdf")
344
+ requested_rows = (
345
+ asf_row_indices
346
+ if asf_row_indices is not None
347
+ else [block.asf_row_indices.tolist() for block in mix_data.blocks]
348
+ )
349
+ summary = summarize_coupling_ci_squared(
350
+ csfs_df,
351
+ mix_data,
352
+ [list(dict.fromkeys(rows)) for rows in requested_rows],
353
+ coupling_level,
354
+ include_members=False,
355
+ allow_empty_blocks=True,
356
+ )
357
+ by_asf = summary.partition_by(["block_id", "asf_index"], as_dict=True)
358
+ used_stems: set[str] = set()
359
+ paths: list[Path] = []
360
+ for block, rows in zip(mix_data.blocks, requested_rows, strict=True):
361
+ for row in rows:
362
+ series = _series_from_summary(
363
+ by_asf[(block.block_index, row)],
364
+ block,
365
+ row,
366
+ min_csf_percentage,
367
+ min_contribution,
368
+ max_channels,
369
+ )
370
+ stem = mid_coupling_output_stem(
371
+ parity=block.parity, asf_row_index=row, j_value=block.j_value
372
+ )
373
+ if stem in used_stems:
374
+ stem = f"{stem}_b{block.block_index + 1}"
375
+ used_stems.add(stem)
376
+ for fmt in formats:
377
+ paths.append(
378
+ plot_mid_coupling_contribution(series, output_dir / f"{stem}.{fmt}")
379
+ )
380
+ return paths
381
+
382
+
296
383
  __all__ = [
297
384
  "MidCouplingPlotSeries",
298
385
  "build_mid_coupling_plot_series",
299
386
  "plot_mid_coupling_contribution",
387
+ "mid_coupling_output_stem",
388
+ "save_mid_coupling_plots",
300
389
  ]
File without changes