graspkit-atomic 3.5.2__tar.gz → 3.5.3__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.5.3}/INSTALL.md +6 -7
  2. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/PKG-INFO +7 -8
  3. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/README.md +6 -7
  4. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/README_zh.md +5 -5
  5. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/docs/releasing.md +13 -7
  6. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/__init__.py +4 -0
  7. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/coupling.py +132 -103
  8. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/validation.py +3 -1
  9. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/version.py +1 -1
  10. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit_plot/__init__.py +2 -0
  11. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit_plot/mid_coupling.py +116 -27
  12. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/.gitignore +0 -0
  13. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/LICENSE +0 -0
  14. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/build_package.py +0 -0
  15. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/docs/csf-selection-primitives.md +0 -0
  16. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/pyproject.toml +0 -0
  17. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/scripts/check_release.py +0 -0
  18. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/coverage.py +0 -0
  19. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/extraction.py +0 -0
  20. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/mr_selection.py +0 -0
  21. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/CSFs_processor/selection.py +0 -0
  22. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/__init__.py +0 -0
  23. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/__init__.py +0 -0
  24. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/file_locator.py +0 -0
  25. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/__init__.py +0 -0
  26. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/base_loader.py +0 -0
  27. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/binary_file_loader.py +0 -0
  28. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/energy_file_loader.py +0 -0
  29. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/gj_factor_loader.py +0 -0
  30. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/hyperfine_structure_loader.py +0 -0
  31. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/lsj_comp_loader.py +0 -0
  32. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/mix_coef_loader.py +0 -0
  33. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/radial_analysis_loader.py +0 -0
  34. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/radial_wavefunction_loader.py +0 -0
  35. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/loaders/transition_loader.py +0 -0
  36. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/mix_coef_writer.py +0 -0
  37. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/data_IO/produced_data_writor.py +0 -0
  38. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/__init__.py +0 -0
  39. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/asfs_data_processor.py +0 -0
  40. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/radial_analysis.py +0 -0
  41. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/radial_wavefunction_processor.py +0 -0
  42. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/rmix_data_processor.py +0 -0
  43. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/grasp_data_extractor/transition_data_processor.py +0 -0
  44. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/py.typed +0 -0
  45. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/utils/__init__.py +0 -0
  46. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/utils/data_modules.py +0 -0
  47. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/utils/environment_config.py +0 -0
  48. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/utils/quadrupole_deformation.py +0 -0
  49. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit/utils/tool_function.py +0 -0
  50. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit_plot/fig_settings.py +0 -0
  51. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit_plot/plot_functions.py +0 -0
  52. {graspkit_atomic-3.5.2 → graspkit_atomic-3.5.3}/src/graspkit_plot/radial_analysis.py +0 -0
@@ -6,10 +6,9 @@ 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.5.3 with cumulative coupling-channel selection and batch plots for selected ASFs.
11
10
  Use this source checkout until publication; the pinned PyPI examples below
12
- apply after 3.5.2 is available on the package index.
11
+ apply after 3.5.3 is available on the package index.
13
12
 
14
13
  ## Install from PyPI
15
14
 
@@ -20,12 +19,12 @@ python -m pip install graspkit-atomic
20
19
  For a fixed release:
21
20
 
22
21
  ```bash
23
- python -m pip install "graspkit-atomic==3.5.2"
22
+ python -m pip install "graspkit-atomic==3.5.3"
24
23
  ```
25
24
 
26
25
  ## Declare a project dependency
27
26
 
28
- Add `"graspkit-atomic==3.5.2"` to the existing `[project].dependencies` list in
27
+ Add `"graspkit-atomic==3.5.3"` to the existing `[project].dependencies` list in
29
28
  your own `pyproject.toml`. A minimal example:
30
29
 
31
30
  ```toml
@@ -33,7 +32,7 @@ your own `pyproject.toml`. A minimal example:
33
32
  name = "atomic-analysis"
34
33
  version = "0.1.0"
35
34
  requires-python = ">=3.15"
36
- dependencies = ["graspkit-atomic==3.5.2"]
35
+ dependencies = ["graspkit-atomic==3.5.3"]
37
36
  ```
38
37
 
39
38
  For a uv-managed project, run `uv sync` after editing `pyproject.toml`, then
@@ -52,7 +51,7 @@ requires the corresponding GRASP data files.
52
51
  To install a downloaded wheel, use its exact filename:
53
52
 
54
53
  ```bash
55
- python -m pip install /path/to/graspkit_atomic-3.5.2-py3-none-any.whl
54
+ python -m pip install /path/to/graspkit_atomic-3.5.3-py3-none-any.whl
56
55
  ```
57
56
 
58
57
  A standalone source checkout also supports `python -m pip install .`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: graspkit-atomic
3
- Version: 3.5.2
3
+ Version: 3.5.3
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.5.3 adds cumulative coupling-channel selection and batch plotting
67
+ for selected ASFs. See the [release notes](docs/releasing.md#changes-in-353)
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.5.3 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`;
@@ -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
+ To pin a particular release, use `uv add "graspkit-atomic==3.5.3"`.
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.5.3",
106
105
  ]
107
106
  ```
108
107
 
@@ -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.5.3 adds cumulative coupling-channel selection and batch plotting
20
+ for selected ASFs. See the [release notes](docs/releasing.md#changes-in-353)
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.5.3 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`;
@@ -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
+ To pin a particular release, use `uv add "graspkit-atomic==3.5.3"`.
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.5.3",
59
58
  ]
60
59
  ```
61
60
 
@@ -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.5.3 支持按累计 CI² 与主导耦合通道联合筛选 CSF,并为选定的 ASF 批量绘图。
16
+ 详见[版本说明](docs/releasing.md#changes-in-353)和[CSF 处理接口文档](docs/csf-selection-primitives.md)。
17
17
 
18
18
  ## 安装
19
19
 
20
- Python 3.15 / Polars 2.1 兼容修改尚未发布,请暂用源码版本。
20
+ 3.5.3 发布前可使用本版源码安装。
21
21
 
22
22
  使用 Python 3.15 或更新版本,从 [PyPI 安装 graspkit-atomic](https://pypi.org/project/graspkit-atomic/)。
23
23
  分发包名为 `graspkit-atomic`,Python 导入名为 `graspkit` 和 `graspkit_plot`。
@@ -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
+ 需要固定版本时,使用 `uv add "graspkit-atomic==3.5.3"`。
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.5.3",
50
50
  ]
51
51
  ```
52
52
 
@@ -1,11 +1,17 @@
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 stable version is **3.5.3**. 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.5.3
9
+
10
+ - `select_csfs_by_cumulative_coupling` takes the union of each selected ASF's
11
+ cumulative CI² prefix and the CSFs in its dominant coupling channel.
12
+ - `save_mid_coupling_plots` groups CSFs once and writes a plot for each requested
13
+ ASF in SVG, PNG, or PDF format.
14
+
9
15
  ## Changes in 3.5.2
10
16
 
11
17
  - Provide deterministic per-ASF cumulative CI-squared selection and diagnostics.
@@ -54,8 +60,8 @@ The obsolete `--dev` option is removed; edit the version source deliberately.
54
60
  `--clean` removes only matching graspkit-atomic archives from the selected output
55
61
  folder. Unknown files cause an error instead of being deleted.
56
62
 
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
63
+ Output: `dist/graspkit_atomic-3.5.3.tar.gz` and
64
+ `dist/graspkit_atomic-3.5.3-py3-none-any.whl`. An optional `--outdir PATH` selects an
59
65
  empty output folder. The shell/batch wrappers select the shared Tools Python.
60
66
 
61
67
  Equivalent individual checks:
@@ -111,7 +117,7 @@ with a branch selector. Review all three platform jobs before using the artifact
111
117
  ## Before a later publication
112
118
 
113
119
  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
120
+ 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.5.3
115
121
  has not already been published. A missing public project page alone does
116
122
  not prove that a name is available.
117
123
  3. Inspect the actual archives and hashes. Publishing makes their contents
@@ -135,7 +141,7 @@ completing a build does not start a publication. Its inputs are:
135
141
 
136
142
  | Input | Default | Purpose |
137
143
  | --- | --- | --- |
138
- | `version` | Required | Exact source version, currently `3.5.2`. |
144
+ | `version` | Required | Exact source version, currently `3.5.3`. |
139
145
  | `publish_pypi` | Off | Upload the validated packages to PyPI. |
140
146
  | `github_release` | Off | Create a GitHub Release using the same packages. |
141
147
  | `draft` | On | Keep the GitHub Release as a draft; turn off only for formal publication. |
@@ -151,7 +157,7 @@ source version, and select the destinations you intend to use:
151
157
  | On | On | Build and validate once, then upload the same files to both destinations. |
152
158
 
153
159
  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`.
160
+ needed. The GitHub tag is derived as `v{version}`, for example `v3.5.3`.
155
161
  The `draft` option has no effect when `github_release` is off.
156
162
 
157
163
  ### 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
@@ -3,6 +3,8 @@
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ from collections.abc import Iterator
7
+ from dataclasses import dataclass
6
8
  from fractions import Fraction
7
9
 
8
10
  import numpy as np
@@ -10,6 +12,7 @@ from numpy.typing import NDArray
10
12
  import polars as pl
11
13
 
12
14
  from ..utils.data_modules import MixCoefficientData
15
+ from .selection import select_csf_indices_by_cumulative_weight
13
16
  from .validation import (
14
17
  normalize_asf_row_indices,
15
18
  validate_coupling_level,
@@ -129,11 +132,14 @@ def _selected_block_coefficients(
129
132
  csfs_df: pl.DataFrame,
130
133
  asfs_mix_data: MixCoefficientData,
131
134
  asf_row_indices: list[list[int]] | None,
132
- ) -> list[tuple[int, list[int], NDArray[np.float64]]]:
135
+ *,
136
+ allow_empty_blocks: bool = False,
137
+ ) -> Iterator[tuple[int, list[int], NDArray[np.float64]]]:
133
138
  """Validate J/CSF alignment and return selected ASF coefficient matrices."""
134
139
  normalized_positions = normalize_asf_row_indices(
135
140
  asfs_mix_data,
136
141
  asf_row_indices,
142
+ allow_empty_blocks=allow_empty_blocks,
137
143
  )
138
144
  dataframe_block_ids = (
139
145
  csfs_df.get_column("block_id").unique(maintain_order=True).to_list()
@@ -144,7 +150,6 @@ def _selected_block_coefficients(
144
150
  f"CSF block IDs {dataframe_block_ids} 与 rmix block IDs {mix_block_ids} 不一致"
145
151
  )
146
152
 
147
- selected_blocks: list[tuple[int, list[int], NDArray[np.float64]]] = []
148
153
  for mix_block, mix_j_value, selected_positions in zip(
149
154
  asfs_mix_data.blocks,
150
155
  asfs_mix_data.level_J_value_list,
@@ -160,21 +165,16 @@ def _selected_block_coefficients(
160
165
  f"Block {mix_block.block_index}: mixing coefficients 必须是二维矩阵"
161
166
  )
162
167
 
163
- dataframe_block = csfs_df.filter(
164
- pl.col("block_id") == mix_block.block_index
168
+ signatures = csfs_df[_COUPLING_SIGNATURE_COLUMN].filter(
169
+ csfs_df["block_id"] == mix_block.block_index
165
170
  )
166
- dataframe_csf_count = dataframe_block.height
171
+ dataframe_csf_count = len(signatures)
167
172
  if coefficient_matrix.shape[1] != dataframe_csf_count:
168
173
  raise ValueError(
169
174
  f"Block {mix_block.block_index}: rmix CSF 数量 {coefficient_matrix.shape[1]} 与 CSF DataFrame {dataframe_csf_count} 不一致"
170
175
  )
171
176
 
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
- )
177
+ csf_two_j_values = signatures.list.last().unique(maintain_order=True).to_list()
178
178
  if len(csf_two_j_values) != 1:
179
179
  raise ValueError(
180
180
  f"Block {mix_block.block_index}: CSF DataFrame 包含多个总 J: 2J={csf_two_j_values}"
@@ -186,14 +186,11 @@ def _selected_block_coefficients(
186
186
  f"Block {mix_block.block_index}: CSF J={_format_twice_j(csf_two_j)} 与 rmix J={mix_j_value} 不一致"
187
187
  )
188
188
 
189
- selected_blocks.append(
190
- (
191
- mix_block.block_index,
192
- selected_positions,
193
- coefficient_matrix[selected_positions],
194
- )
189
+ yield (
190
+ mix_block.block_index,
191
+ selected_positions,
192
+ coefficient_matrix[selected_positions],
195
193
  )
196
- return selected_blocks
197
194
 
198
195
 
199
196
  def _twice_j_value(j_value: str, *, block_index: int) -> int:
@@ -216,53 +213,38 @@ def _format_twice_j(two_j: int) -> str:
216
213
  return f"{two_j}/2"
217
214
 
218
215
 
219
- def _mixing_coefficients_to_long_frame(
216
+ @dataclass(frozen=True)
217
+ class _WeightedCouplingBlock:
218
+ block_id: int
219
+ asf_rows: list[int]
220
+ groups: pl.DataFrame
221
+ ci_squared: NDArray[np.float64]
222
+ channel_sums: NDArray[np.float64]
223
+
224
+
225
+ def _weighted_coupling_blocks(
220
226
  csfs_df: pl.DataFrame,
221
- asfs_mix_data: MixCoefficientData,
227
+ mix_data: MixCoefficientData,
222
228
  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")
229
+ coupling_level: int | None,
230
+ *,
231
+ allow_empty_blocks: bool = False,
232
+ ) -> Iterator[_WeightedCouplingBlock]:
233
+ """Group each CSF once, then sum each ASF over the same source-ordered members."""
234
+ groups = collect_coupling_groups(csfs_df, coupling_level)
235
+ for block_id, rows, coefficients in _selected_block_coefficients(
236
+ csfs_df, mix_data, asf_row_indices, allow_empty_blocks=allow_empty_blocks
237
+ ):
238
+ if not rows:
239
+ continue
240
+ block_groups = groups.filter(pl.col("block_id") == block_id)
241
+ members = block_groups["idxs"].explode().to_numpy()
242
+ counts = block_groups["count"].to_numpy()
243
+ starts = np.cumsum(counts, dtype=np.int64) - counts
244
+ weights = np.square(coefficients)
245
+ # Reduce one ASF at a time to bound temporary storage by the block size.
246
+ sums = np.stack([np.add.reduceat(row[members], starts) for row in weights])
247
+ yield _WeightedCouplingBlock(block_id, rows, block_groups, weights, sums)
266
248
 
267
249
 
268
250
  def summarize_coupling_ci_squared(
@@ -270,56 +252,103 @@ def summarize_coupling_ci_squared(
270
252
  asfs_mix_data: MixCoefficientData,
271
253
  asf_row_indices: list[list[int]] | None = None,
272
254
  coupling_level: int | None = None,
255
+ *,
256
+ include_members: bool = True,
257
+ allow_empty_blocks: bool = False,
273
258
  ) -> pl.DataFrame:
274
- """Summarize CI-square contributions by block, ASF, and coupling pattern.
259
+ """Return channel counts and CI² sums in block, ASF and source-channel order.
275
260
 
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.
261
+ By default also return the block-local and source indices of each member.
262
+ For plots, omit the member lists and allow empty ASF lists to skip blocks.
279
263
  """
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(
264
+ frames: list[pl.DataFrame] = []
265
+ for block in _weighted_coupling_blocks(
288
266
  csfs_df,
289
267
  asfs_mix_data,
290
268
  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 未能完整对齐")
269
+ coupling_level,
270
+ allow_empty_blocks=allow_empty_blocks,
271
+ ):
272
+ groups = (
273
+ block.groups
274
+ if include_members
275
+ else block.groups.drop("idxs", "global_idxs")
276
+ )
277
+ for asf_index, channel_sums in zip(
278
+ block.asf_rows, block.channel_sums, strict=True
279
+ ):
280
+ frames.append(
281
+ groups.with_columns(
282
+ pl.lit(asf_index, dtype=pl.Int64).alias("asf_index"),
283
+ pl.Series("sum_ci", channel_sums),
284
+ )
285
+ )
286
+ schema: dict[str, type[pl.DataType] | pl.DataType] = {
287
+ "block_id": pl.UInt32,
288
+ "asf_index": pl.Int64,
289
+ "coupling_signature": pl.List(pl.Int32),
290
+ "count": pl.UInt32,
291
+ }
292
+ if include_members:
293
+ schema.update(idxs=pl.List(pl.UInt64), global_idxs=pl.List(pl.UInt64))
294
+ schema["sum_ci"] = pl.Float64
295
+ if not frames:
296
+ return pl.DataFrame(schema=schema)
297
+ return pl.concat(frames).select(list(schema)).cast({"block_id": pl.UInt32})
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class CumulativeCouplingSelection:
302
+ """Source-ordered selection and the statistics used to construct it."""
303
+
304
+ selected_csfs: pl.DataFrame
305
+ prefix_counts: dict[int, int]
306
+ dominant_channels: pl.DataFrame
307
+
308
+
309
+ def select_csfs_by_cumulative_coupling(
310
+ csfs_df: pl.DataFrame,
311
+ mix_data: MixCoefficientData,
312
+ *,
313
+ cumulative_threshold: float,
314
+ coupling_level: int,
315
+ asf_row_indices: list[list[int]] | None = None,
316
+ ) -> CumulativeCouplingSelection:
317
+ """Union each selected ASF's normalized CI² prefix and its dominant channel.
301
318
 
302
- return (
303
- joined.group_by(
304
- ["block_id", "asf_index", _SELECTED_COUPLING_COLUMN],
305
- maintain_order=True,
319
+ Prefix ties follow select_csf_indices_by_cumulative_weight. Equal channel
320
+ sums select the first channel in CSF source order, as in ML presampling.
321
+ """
322
+ selected = np.zeros(csfs_df.height, dtype=np.bool_)
323
+ prefix_counts: dict[int, int] = {}
324
+ dominant_frames: list[pl.DataFrame] = []
325
+ for block in _weighted_coupling_blocks(
326
+ csfs_df, mix_data, asf_row_indices, coupling_level
327
+ ):
328
+ prefix = select_csf_indices_by_cumulative_weight(
329
+ block.ci_squared, cumulative_threshold=cumulative_threshold
306
330
  )
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"),
331
+ prefix_counts[block.block_id] = len(prefix.indices)
332
+ winners = np.argmax(block.channel_sums, axis=1)
333
+ block_mask = np.zeros(block.ci_squared.shape[1], dtype=np.bool_)
334
+ block_mask[prefix.indices] = True
335
+ theme_members = (
336
+ block.groups["idxs"].gather(np.unique(winners)).explode().to_numpy()
312
337
  )
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",
338
+ block_mask[theme_members] = True
339
+ selected[csfs_df["block_id"].to_numpy() == block.block_id] = block_mask
340
+ dominant_frames.append(
341
+ block.groups.select("block_id", "coupling_signature", "count")[
342
+ winners
343
+ ].with_columns(
344
+ pl.Series("asf_index", block.asf_rows, dtype=pl.Int64),
345
+ pl.Series(
346
+ "sum_ci", block.channel_sums[np.arange(len(winners)), winners]
347
+ ),
348
+ )
322
349
  )
350
+ return CumulativeCouplingSelection(
351
+ csfs_df.filter(selected), prefix_counts, pl.concat(dominant_frames)
323
352
  )
324
353
 
325
354
 
@@ -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.5.3"
@@ -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