graspkit-atomic 3.4.4__tar.gz → 3.5.2__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.4.4 → graspkit_atomic-3.5.2}/INSTALL.md +11 -6
  2. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/PKG-INFO +19 -12
  3. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/README.md +13 -6
  4. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/README_zh.md +11 -6
  5. graspkit_atomic-3.5.2/docs/csf-selection-primitives.md +100 -0
  6. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/docs/releasing.md +32 -9
  7. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/pyproject.toml +9 -6
  8. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/scripts/check_release.py +3 -1
  9. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/__init__.py +19 -0
  10. graspkit_atomic-3.5.2/src/graspkit/CSFs_processor/coverage.py +112 -0
  11. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/selection.py +173 -32
  12. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/validation.py +13 -6
  13. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/mix_coef_loader.py +6 -2
  14. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/mix_coef_writer.py +2 -1
  15. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/asfs_data_processor.py +1 -1
  16. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/rmix_data_processor.py +14 -5
  17. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/utils/data_modules.py +1 -0
  18. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/version.py +1 -1
  19. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/.gitignore +0 -0
  20. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/LICENSE +0 -0
  21. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/build_package.py +0 -0
  22. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/coupling.py +0 -0
  23. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/extraction.py +0 -0
  24. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/CSFs_processor/mr_selection.py +0 -0
  25. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/__init__.py +0 -0
  26. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/__init__.py +0 -0
  27. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/file_locator.py +0 -0
  28. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/__init__.py +0 -0
  29. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/base_loader.py +0 -0
  30. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/binary_file_loader.py +0 -0
  31. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/energy_file_loader.py +0 -0
  32. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/gj_factor_loader.py +0 -0
  33. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/hyperfine_structure_loader.py +0 -0
  34. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/lsj_comp_loader.py +0 -0
  35. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/radial_analysis_loader.py +0 -0
  36. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/radial_wavefunction_loader.py +0 -0
  37. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/loaders/transition_loader.py +0 -0
  38. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/data_IO/produced_data_writor.py +0 -0
  39. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/__init__.py +0 -0
  40. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/radial_analysis.py +0 -0
  41. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/radial_wavefunction_processor.py +0 -0
  42. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/grasp_data_extractor/transition_data_processor.py +0 -0
  43. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/py.typed +0 -0
  44. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/utils/__init__.py +0 -0
  45. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/utils/environment_config.py +0 -0
  46. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/utils/quadrupole_deformation.py +0 -0
  47. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit/utils/tool_function.py +0 -0
  48. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit_plot/__init__.py +0 -0
  49. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit_plot/fig_settings.py +0 -0
  50. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit_plot/mid_coupling.py +0 -0
  51. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit_plot/plot_functions.py +0 -0
  52. {graspkit_atomic-3.4.4 → graspkit_atomic-3.5.2}/src/graspkit_plot/radial_analysis.py +0 -0
@@ -1,11 +1,16 @@
1
1
  # Installation
2
2
 
3
- `graspkit-atomic` requires Python 3.14 or newer. It provides the `graspkit` and
3
+ This development checkout of `graspkit-atomic` requires Python 3.15 or newer. It provides the `graspkit` and
4
4
  `graspkit_plot` import packages. The distribution name is `graspkit-atomic`, previously `grasp-atomic-kit`;
5
5
  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.
11
+ Use this source checkout until publication; the pinned PyPI examples below
12
+ apply after 3.5.2 is available on the package index.
13
+
9
14
  ## Install from PyPI
10
15
 
11
16
  ```bash
@@ -15,20 +20,20 @@ python -m pip install graspkit-atomic
15
20
  For a fixed release:
16
21
 
17
22
  ```bash
18
- python -m pip install "graspkit-atomic==3.4.4"
23
+ python -m pip install "graspkit-atomic==3.5.2"
19
24
  ```
20
25
 
21
26
  ## Declare a project dependency
22
27
 
23
- Add `"graspkit-atomic==3.4.4"` to the existing `[project].dependencies` list in
28
+ Add `"graspkit-atomic==3.5.2"` to the existing `[project].dependencies` list in
24
29
  your own `pyproject.toml`. A minimal example:
25
30
 
26
31
  ```toml
27
32
  [project]
28
33
  name = "atomic-analysis"
29
34
  version = "0.1.0"
30
- requires-python = ">=3.14"
31
- dependencies = ["graspkit-atomic==3.4.4"]
35
+ requires-python = ">=3.15"
36
+ dependencies = ["graspkit-atomic==3.5.2"]
32
37
  ```
33
38
 
34
39
  For a uv-managed project, run `uv sync` after editing `pyproject.toml`, then
@@ -47,7 +52,7 @@ requires the corresponding GRASP data files.
47
52
  To install a downloaded wheel, use its exact filename:
48
53
 
49
54
  ```bash
50
- python -m pip install /path/to/graspkit_atomic-3.4.4-py3-none-any.whl
55
+ python -m pip install /path/to/graspkit_atomic-3.5.2-py3-none-any.whl
51
56
  ```
52
57
 
53
58
  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.4.4
3
+ Version: 3.5.2
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
@@ -12,15 +12,15 @@ Keywords: GRASP,atomic physics,data processing,plotting
12
12
  Classifier: Development Status :: 5 - Production/Stable
13
13
  Classifier: Intended Audience :: Science/Research
14
14
  Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
16
  Classifier: Topic :: Scientific/Engineering :: Physics
17
- Requires-Python: >=3.14
17
+ Requires-Python: >=3.15
18
18
  Requires-Dist: cycler>=0.12.1
19
- Requires-Dist: matplotlib>=3.10.8
19
+ Requires-Dist: matplotlib>=3.11.2
20
20
  Requires-Dist: numpy>=2.4.2
21
- Requires-Dist: polars>=1.38.1
21
+ Requires-Dist: polars>=2.1.0
22
22
  Requires-Dist: rich>=14.3.3
23
- Requires-Dist: rtoml>=0.13.0
23
+ Requires-Dist: rtoml>=0.14.0
24
24
  Provides-Extra: all
25
25
  Requires-Dist: basedpyright>=1.34.0; extra == 'all'
26
26
  Requires-Dist: build>=1.4.0; extra == 'all'
@@ -63,10 +63,17 @@ 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.
69
+
66
70
  ## Installation
67
71
 
72
+ The Python 3.15 / Polars 2.1 compatibility changes are unreleased; use this
73
+ source checkout until the next package release.
74
+
68
75
  Install [graspkit-atomic from PyPI](https://pypi.org/project/graspkit-atomic/)
69
- with Python 3.14 or newer. The distribution name is `graspkit-atomic`;
76
+ with Python 3.15 or newer. The distribution name is `graspkit-atomic`;
70
77
  its Python import packages are `graspkit` and `graspkit_plot`.
71
78
 
72
79
  ### With uv
@@ -75,17 +82,17 @@ Use [uv](https://docs.astral.sh/uv/getting-started/installation/) to manage the
75
82
  environment and dependencies of your own analysis project. For a new project:
76
83
 
77
84
  ```bash
78
- uv init --python 3.14 atomic-analysis
85
+ uv init --python 3.15 atomic-analysis
79
86
  cd atomic-analysis
80
87
  uv add graspkit-atomic
81
88
  uv run python -c "import graspkit; print(graspkit.__version__)"
82
89
  ```
83
90
 
84
- For an existing uv project using Python 3.14 or newer, run `uv add graspkit-atomic`
91
+ For an existing uv project using Python 3.15 or newer, run `uv add graspkit-atomic`
85
92
  in its directory. This records the dependency in `pyproject.toml`, updates
86
93
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
87
94
  to run your own analysis script; manual environment activation is not required.
88
- To pin a particular release, use `uv add "graspkit-atomic==3.4.4"`.
95
+ To pin a particular release, use `uv add "graspkit-atomic==3.5.2"`.
89
96
 
90
97
  You can also add the dependency to an existing `pyproject.toml` manually:
91
98
 
@@ -93,9 +100,9 @@ You can also add the dependency to an existing `pyproject.toml` manually:
93
100
  [project]
94
101
  name = "atomic-analysis"
95
102
  version = "0.1.0"
96
- requires-python = ">=3.14"
103
+ requires-python = ">=3.15"
97
104
  dependencies = [
98
- "graspkit-atomic==3.4.4",
105
+ "graspkit-atomic==3.5.2",
99
106
  ]
100
107
  ```
101
108
 
@@ -16,10 +16,17 @@ 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.
22
+
19
23
  ## Installation
20
24
 
25
+ The Python 3.15 / Polars 2.1 compatibility changes are unreleased; use this
26
+ source checkout until the next package release.
27
+
21
28
  Install [graspkit-atomic from PyPI](https://pypi.org/project/graspkit-atomic/)
22
- with Python 3.14 or newer. The distribution name is `graspkit-atomic`;
29
+ with Python 3.15 or newer. The distribution name is `graspkit-atomic`;
23
30
  its Python import packages are `graspkit` and `graspkit_plot`.
24
31
 
25
32
  ### With uv
@@ -28,17 +35,17 @@ Use [uv](https://docs.astral.sh/uv/getting-started/installation/) to manage the
28
35
  environment and dependencies of your own analysis project. For a new project:
29
36
 
30
37
  ```bash
31
- uv init --python 3.14 atomic-analysis
38
+ uv init --python 3.15 atomic-analysis
32
39
  cd atomic-analysis
33
40
  uv add graspkit-atomic
34
41
  uv run python -c "import graspkit; print(graspkit.__version__)"
35
42
  ```
36
43
 
37
- For an existing uv project using Python 3.14 or newer, run `uv add graspkit-atomic`
44
+ For an existing uv project using Python 3.15 or newer, run `uv add graspkit-atomic`
38
45
  in its directory. This records the dependency in `pyproject.toml`, updates
39
46
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
40
47
  to run your own analysis script; manual environment activation is not required.
41
- To pin a particular release, use `uv add "graspkit-atomic==3.4.4"`.
48
+ To pin a particular release, use `uv add "graspkit-atomic==3.5.2"`.
42
49
 
43
50
  You can also add the dependency to an existing `pyproject.toml` manually:
44
51
 
@@ -46,9 +53,9 @@ You can also add the dependency to an existing `pyproject.toml` manually:
46
53
  [project]
47
54
  name = "atomic-analysis"
48
55
  version = "0.1.0"
49
- requires-python = ">=3.14"
56
+ requires-python = ">=3.15"
50
57
  dependencies = [
51
- "graspkit-atomic==3.4.4",
58
+ "graspkit-atomic==3.5.2",
52
59
  ]
53
60
  ```
54
61
 
@@ -12,9 +12,14 @@
12
12
  - `graspkit.utils`:通用 GRASP 数据模型、环境检测和量子数工具。
13
13
  - `graspkit_plot`:绘图和出版级样式工具。
14
14
 
15
+ 3.5.2 的 CI² 累计筛选、索引映射与轨道覆盖接口见
16
+ [CSF 处理接口文档](docs/csf-selection-primitives.md)。这些新增接口尚未发布,需使用配套源码。
17
+
15
18
  ## 安装
16
19
 
17
- 使用 Python 3.14 或更新版本,从 [PyPI 安装 graspkit-atomic](https://pypi.org/project/graspkit-atomic/)。
20
+ Python 3.15 / Polars 2.1 兼容修改尚未发布,请暂用源码版本。
21
+
22
+ 使用 Python 3.15 或更新版本,从 [PyPI 安装 graspkit-atomic](https://pypi.org/project/graspkit-atomic/)。
18
23
  分发包名为 `graspkit-atomic`,Python 导入名为 `graspkit` 和 `graspkit_plot`。
19
24
 
20
25
  ### 使用 uv 管理项目
@@ -22,16 +27,16 @@
22
27
  可以用 [uv](https://docs.astral.sh/uv/getting-started/installation/) 管理你自己的分析项目环境和依赖。新建项目时:
23
28
 
24
29
  ```bash
25
- uv init --python 3.14 atomic-analysis
30
+ uv init --python 3.15 atomic-analysis
26
31
  cd atomic-analysis
27
32
  uv add graspkit-atomic
28
33
  uv run python -c "import graspkit; print(graspkit.__version__)"
29
34
  ```
30
35
 
31
- 已有 uv 项目使用 Python 3.14 或更新版本时,直接在其目录运行 `uv add graspkit-atomic`。
36
+ 已有 uv 项目使用 Python 3.15 或更新版本时,直接在其目录运行 `uv add graspkit-atomic`。
32
37
  该命令会将依赖写入 `pyproject.toml`,更新 `uv.lock`,并安装到项目的 `.venv` 中。
33
38
  运行自己的分析脚本时使用 `uv run python analysis.py`,无需手动激活环境。
34
- 需要固定版本时,使用 `uv add "graspkit-atomic==3.4.4"`。
39
+ 需要固定版本时,使用 `uv add "graspkit-atomic==3.5.2"`。
35
40
 
36
41
  也可以手动将依赖加入已有的 `pyproject.toml`:
37
42
 
@@ -39,9 +44,9 @@ uv run python -c "import graspkit; print(graspkit.__version__)"
39
44
  [project]
40
45
  name = "atomic-analysis"
41
46
  version = "0.1.0"
42
- requires-python = ">=3.14"
47
+ requires-python = ">=3.15"
43
48
  dependencies = [
44
- "graspkit-atomic==3.4.4",
49
+ "graspkit-atomic==3.5.2",
45
50
  ]
46
51
  ```
47
52
 
@@ -0,0 +1,100 @@
1
+ # CI weights, CSF indices and orbital coverage
2
+
3
+ Available in the prepared GraspKit 3.5.2 source version.
4
+
5
+ The public functions below belong to `graspkit.CSFs_processor`. They do not
6
+ depend on ML configuration, PyTorch, scikit-learn or a calculation workflow.
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.
9
+
10
+ ## Cumulative selection
11
+
12
+ ```python
13
+ import numpy as np
14
+ from graspkit.CSFs_processor import select_csf_indices_by_cumulative_weight
15
+
16
+ selection = select_csf_indices_by_cumulative_weight(
17
+ np.array([[0.90, 0.09, 0.01], [0.05, 0.90, 0.05]]),
18
+ csf_indices=np.array([10, 20, 30], dtype=np.int64),
19
+ cumulative_threshold=0.99,
20
+ )
21
+ ```
22
+
23
+ The matrix always has ASF rows and CSF columns; a one-dimensional array denotes
24
+ one ASF. Each row is sorted independently, the first item crossing the target
25
+ is included, and the per-ASF prefixes are unioned. Equal weights use descending
26
+ CSF index as a deterministic tie breaker. `csf_indices` optionally maps columns
27
+ to a full pool; without it, indices refer to local columns.
28
+
29
+ `CumulativeCsfSelection` contains `indices`, `per_asf_indices`, original row
30
+ `totals`, and per-ASF `retained_weight`/`discarded_weight` fractions. By default
31
+ the union is sorted by index. `index_order="importance"` preserves the first
32
+ occurrence while visiting each ASF's descending prefix; it is not a joint
33
+ cross-state ranking.
34
+
35
+ - `normalization="unit"` is the default for complete physical ASF coefficients.
36
+ Rows must sum to one within an absolute numerical tolerance of `1e-8`.
37
+ Only rounding-level discrepancies are renormalized.
38
+ - `normalization="relative"` explicitly permits arbitrary finite nonnegative
39
+ totals for post-processing. Zero-total rows yield empty prefixes and zero
40
+ retained/discarded fractions.
41
+ - A target of exactly one keeps every positive input weight. It does not select
42
+ trailing zero entries or overrun the last row because of cumulative rounding.
43
+
44
+ Neither mode certifies energies, other observables or an uncomputed CSF space.
45
+ Do not interpret mixed observations from different CI spaces as one normalized
46
+ wavefunction.
47
+
48
+ `select_ci_cumulative_local_idxs` applies the same kernel to a sequence of
49
+ blocks, with optional per-block ASF **matrix row** selections and concatenated
50
+ block offsets. It uses relative normalization and importance traversal order.
51
+ The existing `rmix_cumulative_selected_row_idxs(RmixCiSquaredData, ...)` delegates
52
+ to this block interface; its loader has already selected the requested ASF rows.
53
+
54
+ ## Indices
55
+
56
+ - `validate_selection_idxs` checks one-dimensional integer indices, bounds,
57
+ duplicates and signed-int64 range.
58
+ - `project_local_idxs_to_full_pool_idxs(source_indices, local_indices)` maps
59
+ local selections through an explicit source-to-pool mapping while preserving
60
+ request order. Both arrays are validated; `pool_row_count` can additionally
61
+ bound the global mapping.
62
+ - `iter_unselected_csf_indices(total_count, excluded_indices, batch_size)` yields
63
+ the sorted complement in bounded chunks, without allocating a full-pool mask.
64
+
65
+ ## Orbital coverage
66
+
67
+ ```python
68
+ from graspkit.CSFs_processor import complete_orbital_coverage
69
+
70
+ occupied = np.array([[True, False], [False, True], [True, True]])
71
+ coverage = complete_orbital_coverage(
72
+ np.array([0], dtype=np.int64),
73
+ read_occupations=lambda indices: occupied[indices],
74
+ total_count=3,
75
+ orbital_count=2,
76
+ batch_size=2,
77
+ )
78
+ assert coverage.added_indices.tolist() == [1]
79
+ ```
80
+
81
+ The reader returns a boolean `(requested CSF, orbital)` matrix in the requested
82
+ index order. A descriptor consumer extracts validated occupation columns;
83
+ models, scaled feature arrays and non-occupation channels do not determine the
84
+ meaning of these masks. Kit neither guesses a descriptor version nor depends
85
+ on the reader's storage implementation.
86
+
87
+ `count_orbital_coverage` counts selected CSFs occupying each requested orbital.
88
+ `complete_orbital_coverage` retains the current selection and visits the index
89
+ complement in source order, adding only rows that cover a remaining gap. This
90
+ is deterministic, not a globally minimum set-cover solver.
91
+
92
+ `OrbitalCoverageResult` returns the selected union, added indices, occupation
93
+ counts and missing orbitals before/after scanning. Uncoverable orbitals remain
94
+ in `missing_after`; EOF is not success. The caller decides whether partial
95
+ coverage is an error. Empty initial selections are supported. If no additions
96
+ are needed, input order is preserved; otherwise the union is index-sorted.
97
+
98
+ This function does not impose a CSF cap, choose which ML candidates may be
99
+ withdrawn, preserve exploration quotas, or change workflow state. Those
100
+ decisions remain in the consuming application.
@@ -1,10 +1,32 @@
1
1
  # Preparing a graspkit-atomic release
2
2
 
3
- The prepared stable version is **3.4.4**. Its single source is
3
+ The prepared stable version is **3.5.2**. 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.
5
6
  The local build commands below do not upload files or create Git tags.
6
7
  The separate manual publishing workflow is described near the end of this guide.
7
8
 
9
+ ## Changes in 3.5.2
10
+
11
+ - Provide deterministic per-ASF cumulative CI-squared selection and diagnostics.
12
+ - Validate and map CSF indices, stream unselected rows, and complete orbital coverage under explicit budgets.
13
+ - Share the cumulative selection kernel with mixing-coefficient processing, independently of ML and workflow state.
14
+
15
+ ## Changes in 3.5.1
16
+
17
+ - Target Python 3.15 and Polars 2.1 in the shared Tools environment.
18
+ - Use the supported full-join API while preserving unmatched energy levels.
19
+ - Update package checks, type-checker environment discovery and release runners.
20
+
21
+ ## Changes in 3.4.5
22
+
23
+ - Read native GRASP odd-parity mixing blocks encoded with ISPAR = -1, fixing
24
+ `Invalid mix coefficient block 1 header` during MR selection.
25
+ - Keep the Python parity convention (1=even, 2=odd) and accept mixing files
26
+ written with the older Python odd-parity encoding of 2.
27
+ - Write split mixing files with GRASP's native signed parity (+1/-1); cover
28
+ populated and zero-ASF blocks with binary read/write regression tests.
29
+
8
30
  ## Changes in 3.4.4
9
31
 
10
32
  - Add exact jj-CSF MR selection with original level-ID mapping, strict amplitude
@@ -32,8 +54,8 @@ The obsolete `--dev` option is removed; edit the version source deliberately.
32
54
  `--clean` removes only matching graspkit-atomic archives from the selected output
33
55
  folder. Unknown files cause an error instead of being deleted.
34
56
 
35
- Output: `dist/graspkit_atomic-3.4.4.tar.gz` and
36
- `dist/graspkit_atomic-3.4.4-py3-none-any.whl`. An optional `--outdir PATH` selects an
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
37
59
  empty output folder. The shell/batch wrappers select the shared Tools Python.
38
60
 
39
61
  Equivalent individual checks:
@@ -56,7 +78,8 @@ test. The CI workflow installs the wheel and dependencies on a fresh runner.
56
78
  ## Files and license
57
79
 
58
80
  The wheel contains `graspkit` and `graspkit_plot`. The source archive includes
59
- those sources, metadata, GPLv3 text and selected installation/build docs.
81
+ those sources, metadata, GPLv3 text, selected installation/build docs and the
82
+ public CSF processing guide.
60
83
  Research notes, agent instructions, tests, local data and historical reports
61
84
  are excluded. Full regression tests remain in the development repository.
62
85
  The existing GPLv3 license is recorded as `GPL-3.0-only`.
@@ -66,12 +89,12 @@ The existing GPLv3 license is recorded as `GPL-3.0-only`.
66
89
  `.github/workflows/build-release.yml` runs by manual dispatch or by an explicit
67
90
  push to a `codex/release-build-check-*` branch. It is also reusable through
68
91
  `workflow_call`, so the publishing workflow builds the same commit. It builds
69
- and checks on Linux, Windows and macOS using Python 3.14, and stores GitHub
92
+ and checks on Linux, Windows and macOS using Python 3.15, and stores GitHub
70
93
  Actions artifacts. It has no PyPI credentials, OIDC publishing permission,
71
94
  publish job or tag-triggered upload. CI uses an ephemeral standalone runner;
72
95
  it does not create a second runtime in this paired local workspace.
73
96
  A universal wheel still relies on its dependencies supporting the target OS.
74
- Python versions above 3.14 are permitted by metadata but not yet in this matrix.
97
+ Python versions above 3.15 are permitted by metadata but not yet in this matrix.
75
98
 
76
99
  Until the workflow reaches the default branch, start a check from the release
77
100
  commit by pushing it to a dedicated branch, for example:
@@ -88,7 +111,7 @@ with a branch selector. Review all three platform jobs before using the artifact
88
111
  ## Before a later publication
89
112
 
90
113
  1. Review the exact source commit and release changes; rerun the workflow on it.
91
- 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.4.4
114
+ 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.5.2
92
115
  has not already been published. A missing public project page alone does
93
116
  not prove that a name is available.
94
117
  3. Inspect the actual archives and hashes. Publishing makes their contents
@@ -112,7 +135,7 @@ completing a build does not start a publication. Its inputs are:
112
135
 
113
136
  | Input | Default | Purpose |
114
137
  | --- | --- | --- |
115
- | `version` | Required | Exact source version, currently `3.4.4`. |
138
+ | `version` | Required | Exact source version, currently `3.5.2`. |
116
139
  | `publish_pypi` | Off | Upload the validated packages to PyPI. |
117
140
  | `github_release` | Off | Create a GitHub Release using the same packages. |
118
141
  | `draft` | On | Keep the GitHub Release as a draft; turn off only for formal publication. |
@@ -128,7 +151,7 @@ source version, and select the destinations you intend to use:
128
151
  | On | On | Build and validate once, then upload the same files to both destinations. |
129
152
 
130
153
  A prior dry run is optional. No separate workflow, run ID or tag input is
131
- needed. The GitHub tag is derived as `v{version}`, for example `v3.4.4`.
154
+ needed. The GitHub tag is derived as `v{version}`, for example `v3.5.2`.
132
155
  The `draft` option has no effect when `github_release` is off.
133
156
 
134
157
  ### One build, two independent destinations
@@ -16,21 +16,21 @@ authors = [
16
16
  classifiers = [
17
17
  "Development Status :: 5 - Production/Stable",
18
18
  "Programming Language :: Python :: 3",
19
- "Programming Language :: Python :: 3.14",
19
+ "Programming Language :: Python :: 3.15",
20
20
  "Topic :: Scientific/Engineering :: Physics",
21
21
  "Intended Audience :: Science/Research",
22
22
  ]
23
23
 
24
- requires-python = ">= 3.14"
24
+ requires-python = ">= 3.15"
25
25
 
26
26
  dependencies = [
27
27
  # 核心数据处理库
28
28
  "numpy>=2.4.2",
29
- "polars>=1.38.1",
30
- "matplotlib>=3.10.8",
29
+ "polars>=2.1.0",
30
+ "matplotlib>=3.11.2",
31
31
  "cycler>=0.12.1",
32
32
  # 配置文件处理
33
- "rtoml>=0.13.0",
33
+ "rtoml>=0.14.0",
34
34
  "rich>=14.3.3",
35
35
  ]
36
36
 
@@ -77,6 +77,7 @@ only-include = [
77
77
  "README_zh.md",
78
78
  "INSTALL.md",
79
79
  "docs/releasing.md",
80
+ "docs/csf-selection-primitives.md",
80
81
  "build_package.py",
81
82
  "scripts/check_release.py",
82
83
  ]
@@ -97,13 +98,15 @@ select = ["NPY201"]
97
98
  quote-style = "double"
98
99
 
99
100
  [tool.basedpyright]
101
+ venvPath = "../graspkit-tools"
102
+ venv = ".venv"
100
103
  include = ["src"]
101
104
  exclude = ["**/node_modules",
102
105
  "**/__pycache__",
103
106
  "src/experimental",
104
107
  "src/typestubs"
105
108
  ]
106
- pythonVersion = "3.14"
109
+ pythonVersion = "3.15"
107
110
  typeCheckingMode = "strict"
108
111
  defineConstant = { DEBUG = true }
109
112
 
@@ -43,6 +43,7 @@ SDIST_PATTERNS = {
43
43
  "README_zh.md",
44
44
  "INSTALL.md",
45
45
  "docs/releasing.md",
46
+ "docs/csf-selection-primitives.md",
46
47
  "build_package.py",
47
48
  "scripts/check_release.py",
48
49
  }
@@ -50,6 +51,7 @@ SDIST_REQUIRED = {
50
51
  "pyproject.toml",
51
52
  "LICENSE",
52
53
  "README.md",
54
+ "docs/csf-selection-primitives.md",
53
55
  "src/graspkit/version.py",
54
56
  "src/graspkit/py.typed",
55
57
  "scripts/check_release.py",
@@ -61,7 +63,7 @@ def check_metadata(raw: bytes) -> str:
61
63
  assert metadata["Name"] == NAME, metadata["Name"]
62
64
  version = Version(str(metadata["Version"]))
63
65
  assert not version.is_prerelease and not version.is_devrelease, version
64
- assert str(metadata["Requires-Python"]).replace(" ", "") == ">=3.14"
66
+ assert str(metadata["Requires-Python"]).replace(" ", "") == ">=3.15"
65
67
  assert metadata["License-Expression"] == LICENSE
66
68
  assert metadata["Author-email"] and metadata["Description-Content-Type"]
67
69
  assert len(str(metadata.get_payload()).strip()) > 100, "Missing project description"
@@ -11,7 +11,13 @@ from .extraction import (
11
11
  create_csf_document,
12
12
  write_csf_documents,
13
13
  )
14
+ from .coverage import (
15
+ OrbitalCoverageResult,
16
+ complete_orbital_coverage,
17
+ count_orbital_coverage,
18
+ )
14
19
  from .selection import (
20
+ CumulativeCsfSelection,
15
21
  generate_unique_random_numbers,
16
22
  random_choose_csfs,
17
23
  rmix_cumulative_selected_row_idxs,
@@ -19,6 +25,10 @@ from .selection import (
19
25
  select_csf_indices_by_ci_squared_cutoff,
20
26
  select_csfs_rows,
21
27
  sort_csfs_by_mix_coefficient,
28
+ select_csf_indices_by_cumulative_weight,
29
+ select_ci_cumulative_local_idxs,
30
+ project_local_idxs_to_full_pool_idxs,
31
+ iter_unselected_csf_indices,
22
32
  )
23
33
  from .validation import (
24
34
  load_selection_idxs,
@@ -42,6 +52,15 @@ __all__ = [
42
52
  "random_choose_csfs",
43
53
  "select_csfs_rows",
44
54
  "rmix_cumulative_selected_row_idxs",
55
+ "CumulativeCsfSelection",
56
+ "select_csf_indices_by_cumulative_weight",
57
+ "select_ci_cumulative_local_idxs",
58
+ "project_local_idxs_to_full_pool_idxs",
59
+ "iter_unselected_csf_indices",
60
+ # orbital coverage
61
+ "OrbitalCoverageResult",
62
+ "complete_orbital_coverage",
63
+ "count_orbital_coverage",
45
64
  # extraction
46
65
  "CsfDocument",
47
66
  "create_csf_document",
@@ -0,0 +1,112 @@
1
+ """Deterministic orbital-coverage operations independent of ML and workflows."""
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+ from numpy.typing import NDArray
8
+
9
+ from .selection import iter_unselected_csf_indices
10
+ from .validation import validate_selection_idxs
11
+
12
+ type OccupationReader = Callable[[NDArray[np.int64]], NDArray[np.bool_]]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class OrbitalCoverageResult:
17
+ selected_indices: NDArray[np.int64]
18
+ added_indices: NDArray[np.int64]
19
+ occupation_counts: NDArray[np.int64]
20
+ missing_before: NDArray[np.int64]
21
+ missing_after: NDArray[np.int64]
22
+
23
+
24
+ def _read_occupations(
25
+ reader: OccupationReader,
26
+ indices: NDArray[np.int64],
27
+ orbital_count: int,
28
+ ) -> NDArray[np.bool_]:
29
+ occupied = np.asarray(reader(indices))
30
+ if occupied.dtype != np.bool_ or occupied.shape != (len(indices), orbital_count):
31
+ raise ValueError(
32
+ "Occupation reader must return a boolean (requested CSF, orbital) matrix in requested order"
33
+ )
34
+ return occupied
35
+
36
+
37
+ def count_orbital_coverage(
38
+ indices: np.ndarray,
39
+ *,
40
+ read_occupations: OccupationReader,
41
+ orbital_count: int,
42
+ total_count: int | None = None,
43
+ batch_size: int = 100_000,
44
+ ) -> NDArray[np.int64]:
45
+ """Count selected CSFs occupying each orbital using bounded reads.
46
+
47
+ The reader maps the supplied CSF indices to validated occupation masks.
48
+ It is responsible for extracting occupation columns from the source format;
49
+ no descriptor version, feature scaling, model or configuration is inferred.
50
+ """
51
+ if orbital_count < 0 or batch_size <= 0:
52
+ raise ValueError("orbital_count must be nonnegative and batch_size positive")
53
+ selected = validate_selection_idxs(indices, row_count=total_count)
54
+ counts = np.zeros(orbital_count, dtype=np.int64)
55
+ for start in range(0, len(selected), batch_size):
56
+ batch = selected[start : start + batch_size]
57
+ counts += np.count_nonzero(
58
+ _read_occupations(read_occupations, batch, orbital_count), axis=0
59
+ )
60
+ return counts
61
+
62
+
63
+ def complete_orbital_coverage(
64
+ selected_indices: np.ndarray,
65
+ *,
66
+ read_occupations: OccupationReader,
67
+ total_count: int,
68
+ orbital_count: int,
69
+ batch_size: int = 100_000,
70
+ ) -> OrbitalCoverageResult:
71
+ """Add the first source-order CSFs covering still-missing orbitals.
72
+
73
+ Already selected CSFs are retained. No budget is imposed and no model score
74
+ is used. Uncoverable orbitals are returned in ``missing_after`` for callers
75
+ to report or reject; scanning to EOF is not proof of complete coverage.
76
+ Empty initial selections are allowed. With no additions, input order is
77
+ preserved; after additions the union is sorted by source index.
78
+ """
79
+ if total_count < 0:
80
+ raise ValueError("total_count must be nonnegative")
81
+ selected = validate_selection_idxs(selected_indices, row_count=total_count)
82
+ counts = count_orbital_coverage(
83
+ selected,
84
+ read_occupations=read_occupations,
85
+ orbital_count=orbital_count,
86
+ total_count=total_count,
87
+ batch_size=batch_size,
88
+ )
89
+ missing_before = np.flatnonzero(counts == 0).astype(np.int64)
90
+ added: list[int] = []
91
+ if missing_before.size:
92
+ for candidates in iter_unselected_csf_indices(
93
+ total_count, selected, batch_size
94
+ ):
95
+ masks = _read_occupations(read_occupations, candidates, orbital_count)
96
+ for index, occupied in zip(candidates, masks, strict=True):
97
+ if np.any(occupied & (counts == 0)):
98
+ added.append(int(index))
99
+ counts += occupied
100
+ if np.all(counts > 0):
101
+ break
102
+ if np.all(counts > 0):
103
+ break
104
+ additions = np.asarray(added, dtype=np.int64)
105
+ final = np.union1d(selected, additions) if additions.size else selected.copy()
106
+ return OrbitalCoverageResult(
107
+ final,
108
+ additions,
109
+ counts,
110
+ missing_before,
111
+ np.flatnonzero(counts == 0).astype(np.int64),
112
+ )
@@ -5,6 +5,9 @@ from __future__ import annotations
5
5
 
6
6
  import math
7
7
  import random
8
+ from collections.abc import Iterator, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Literal
8
11
 
9
12
  import numpy as np
10
13
  from numpy.typing import NDArray
@@ -14,12 +17,173 @@ from ..grasp_data_extractor.rmix_data_processor import (
14
17
  RmixCiSquaredData,
15
18
  ci_squared,
16
19
  filter_ci_scores_by_threshold,
20
+ filter_sorted_ci_scores_by_cumulative,
17
21
  sort_ci_scores,
18
22
  )
19
23
  from ..utils.data_modules import MixCoefficientData
20
24
  from .validation import normalize_asf_row_indices, validate_selection_idxs
21
25
 
22
26
 
27
+ @dataclass(frozen=True)
28
+ class CumulativeCsfSelection:
29
+ """Per-ASF prefixes and their union in the caller's CSF index space.
30
+
31
+ Retained/discarded weights are fractions of each input row's total.
32
+ In relative mode, zero-total rows produce empty prefixes and zero fractions.
33
+ These fractions do not certify energies or any uncomputed CSF space.
34
+ """
35
+
36
+ indices: NDArray[np.int64]
37
+ per_asf_indices: tuple[NDArray[np.int64], ...]
38
+ totals: NDArray[np.float64]
39
+ retained_weight: NDArray[np.float64]
40
+ discarded_weight: NDArray[np.float64]
41
+
42
+
43
+ def select_csf_indices_by_cumulative_weight(
44
+ ci_squared_values: np.ndarray,
45
+ *,
46
+ cumulative_threshold: float,
47
+ csf_indices: np.ndarray | None = None,
48
+ normalization: Literal["unit", "relative"] = "unit",
49
+ index_order: Literal["ascending", "importance"] = "ascending",
50
+ ) -> CumulativeCsfSelection:
51
+ """Select each ASF's shortest cumulative prefix, then union the CSFs.
52
+
53
+ Input is (ASF, CSF), or one CSF vector for a single ASF. ``unit`` requires
54
+ complete normalized rows (absolute rounding tolerance 1e-8); ``relative``
55
+ explicitly permits arbitrary nonnegative row totals for post-processing.
56
+ The crossing item is included. Equal weights use CSF-index-descending ties.
57
+ ``csf_indices`` maps columns to a global pool; omitted means local columns.
58
+ No ML configuration, predictions, budgets, or file writes are involved.
59
+ """
60
+ if normalization not in {"unit", "relative"} or index_order not in {
61
+ "ascending",
62
+ "importance",
63
+ }:
64
+ raise ValueError("Invalid normalization or index_order")
65
+ if not math.isfinite(cumulative_threshold) or not 0 < cumulative_threshold <= 1:
66
+ raise ValueError("cumulative_threshold must be in (0, 1]")
67
+ values = np.asarray(ci_squared_values)
68
+ if values.ndim not in (1, 2) or not values.size or np.iscomplexobj(values):
69
+ raise ValueError("Expected non-empty CI² with shape (ASF, CSF)")
70
+ weights = np.atleast_2d(np.asarray(values, dtype=np.float64))
71
+ if not np.isfinite(weights).all() or np.any(weights < 0):
72
+ raise ValueError("CI² must be finite and nonnegative")
73
+ indices = validate_selection_idxs(
74
+ np.arange(weights.shape[1], dtype=np.int64)
75
+ if csf_indices is None
76
+ else csf_indices
77
+ )
78
+ if len(indices) != weights.shape[1]:
79
+ raise ValueError("CSF indices do not match CI² shape (ASF, CSF)")
80
+ totals = np.sum(weights, axis=1, dtype=np.float64)
81
+ if not np.isfinite(totals).all():
82
+ raise ValueError("CI² row totals must be finite")
83
+ if normalization == "unit" and not np.allclose(totals, 1.0, rtol=0, atol=1e-8):
84
+ raise ValueError(f"Complete ASF weights must sum to 1, got {totals.tolist()}")
85
+ per_asf: list[NDArray[np.int64]] = []
86
+ normalized = np.divide(
87
+ weights, totals[:, None], out=np.zeros_like(weights), where=totals[:, None] > 0
88
+ )
89
+ # Normalization can underflow tiny positive entries in relative mode.
90
+ # Sorting original weights keeps every nonzero entry when target == 1.
91
+ for row in weights:
92
+ order = np.lexsort((-indices, -row))
93
+ positions = filter_sorted_ci_scores_by_cumulative(
94
+ row[order], cumulative_threshold
95
+ )
96
+ per_asf.append(indices[order[positions]])
97
+ combined = np.concatenate(per_asf)
98
+ union = (
99
+ np.unique(combined)
100
+ if index_order == "ascending"
101
+ else _unique_preserve_order(combined)
102
+ )
103
+ retained = np.sum(normalized[:, np.isin(indices, union)], axis=1)
104
+ positive = totals > 0
105
+ if np.any(retained[positive] + 1e-12 < cumulative_threshold):
106
+ raise ValueError("Cumulative retention did not meet its target")
107
+ discarded = np.where(positive, np.maximum(0.0, 1.0 - retained), 0.0)
108
+ return CumulativeCsfSelection(union, tuple(per_asf), totals, retained, discarded)
109
+
110
+
111
+ def select_ci_cumulative_local_idxs(
112
+ ci_squared_by_block: Sequence[NDArray[np.float64]],
113
+ *,
114
+ asf_row_indices: list[list[int]] | None,
115
+ cumulative_threshold: float,
116
+ ) -> NDArray[np.int64]:
117
+ """Relative cumulative prefixes in concatenated block-local row space.
118
+
119
+ This post-processing interface preserves the per-ASF importance traversal
120
+ order. ASF requests address actual matrix rows, not original level IDs.
121
+ Zero-total rows are ignored. Missing requested blocks select no rows.
122
+ """
123
+ if not math.isfinite(cumulative_threshold) or not 0 < cumulative_threshold <= 1:
124
+ raise ValueError("cumulative_threshold must be in (0, 1]")
125
+ if asf_row_indices is not None and len(asf_row_indices) > len(ci_squared_by_block):
126
+ raise ValueError("ASF selection contains an unknown block")
127
+ selected: list[NDArray[np.int64]] = []
128
+ offset = 0
129
+ for block, values in enumerate(ci_squared_by_block):
130
+ if values.ndim != 2:
131
+ raise ValueError("Each CI² block must be a 2D (ASF, CSF) array")
132
+ if asf_row_indices is None:
133
+ requested = np.arange(values.shape[0], dtype=np.int64)
134
+ elif block >= len(asf_row_indices) or not asf_row_indices[block]:
135
+ requested = np.empty(0, dtype=np.int64)
136
+ else:
137
+ requested = np.asarray(asf_row_indices[block])
138
+ requested = validate_selection_idxs(requested, row_count=values.shape[0])
139
+ if requested.size:
140
+ result = select_csf_indices_by_cumulative_weight(
141
+ values[requested],
142
+ cumulative_threshold=cumulative_threshold,
143
+ csf_indices=np.arange(offset, offset + values.shape[1], dtype=np.int64),
144
+ normalization="relative",
145
+ index_order="importance",
146
+ )
147
+ selected.append(result.indices)
148
+ offset += values.shape[1]
149
+ return (
150
+ _unique_preserve_order(np.concatenate(selected))
151
+ if selected
152
+ else np.empty(0, dtype=np.int64)
153
+ )
154
+
155
+
156
+ def project_local_idxs_to_full_pool_idxs(
157
+ source_sampled_idxs: np.ndarray,
158
+ local_idxs: np.ndarray,
159
+ *,
160
+ pool_row_count: int | None = None,
161
+ ) -> NDArray[np.int64]:
162
+ """Validate and map selected local rows to unique full-pool indices."""
163
+ source = validate_selection_idxs(source_sampled_idxs, row_count=pool_row_count)
164
+ selected = validate_selection_idxs(local_idxs, row_count=len(source))
165
+ return source[selected]
166
+
167
+
168
+ def iter_unselected_csf_indices(
169
+ total_count: int,
170
+ excluded_indices: np.ndarray,
171
+ batch_size: int,
172
+ ) -> Iterator[NDArray[np.int64]]:
173
+ """Yield the sorted CSF-index complement without a full-pool mask."""
174
+ if total_count < 0 or batch_size <= 0:
175
+ raise ValueError("total_count must be nonnegative and batch_size positive")
176
+ excluded = np.sort(validate_selection_idxs(excluded_indices, row_count=total_count))
177
+ for start in range(0, total_count, batch_size):
178
+ stop = min(start + batch_size, total_count)
179
+ indices = np.arange(start, stop, dtype=np.int64)
180
+ lower, upper = np.searchsorted(excluded, [start, stop])
181
+ mask = np.ones(stop - start, dtype=bool)
182
+ mask[excluded[lower:upper] - start] = False
183
+ if np.any(mask):
184
+ yield indices[mask]
185
+
186
+
23
187
  def select_csf_indices_above_ci_squared_cutoff(
24
188
  coefficients: np.ndarray,
25
189
  *,
@@ -51,9 +215,7 @@ def select_csf_indices_by_ci_squared_cutoff(
51
215
 
52
216
  normalized_rows = normalize_asf_row_indices(asfs_mix_data, asf_row_indices)
53
217
 
54
- for block, selected_rows in zip(
55
- asfs_mix_data.blocks, normalized_rows, strict=True
56
- ):
218
+ for block, selected_rows in zip(asfs_mix_data.blocks, normalized_rows, strict=True):
57
219
  block_data = block.mix_coefficients[selected_rows]
58
220
 
59
221
  squared_scores = ci_squared(block_data)
@@ -190,15 +352,11 @@ def random_choose_csfs(
190
352
  random_idxs = generator.choice(
191
353
  unselected_idxs, size=choose_csfs_num, replace=False
192
354
  )
193
- chosen_csfs_idxs = np.concatenate(
194
- [selected_indices, random_idxs]
195
- )
355
+ chosen_csfs_idxs = np.concatenate([selected_indices, random_idxs])
196
356
  else:
197
357
  chosen_csfs_idxs = selected_indices
198
358
  else:
199
- chosen_csfs_idxs = generator.choice(
200
- all_idxs, size=total_needed, replace=False
201
- )
359
+ chosen_csfs_idxs = generator.choice(all_idxs, size=total_needed, replace=False)
202
360
 
203
361
  unselected_idxs = np.setdiff1d(all_idxs, chosen_csfs_idxs)
204
362
 
@@ -271,28 +429,11 @@ def rmix_cumulative_selected_row_idxs(
271
429
  Raises:
272
430
  ValueError: If no block/ASF selects any CSF.
273
431
  """
274
- selected_by_block = rmix_ci_squared.filter_sorted_ci_scores_by_cumulative(
275
- cumulative_threshold
276
- )
277
-
278
- mapped_by_block: list[NDArray[np.int64]] = []
279
- block_offset = 0
280
- for block_ci_indices, block_ci_squared in zip(
281
- selected_by_block.csf_indices_list,
432
+ selected = select_ci_cumulative_local_idxs(
282
433
  rmix_ci_squared.ci_squared_list,
283
- strict=True,
284
- ):
285
- block_selected = [
286
- np.asarray(asf_ci_indices, dtype=np.int64)
287
- for asf_ci_indices in block_ci_indices
288
- if len(asf_ci_indices) > 0
289
- ]
290
- if block_selected:
291
- block_union = _unique_preserve_order(np.concatenate(block_selected))
292
- mapped_by_block.append(block_union + block_offset)
293
-
294
- block_offset += int(block_ci_squared.shape[1])
295
-
296
- if not mapped_by_block:
434
+ asf_row_indices=None, # The loader has already selected/reordered ASF rows.
435
+ cumulative_threshold=cumulative_threshold,
436
+ )
437
+ if not selected.size:
297
438
  raise ValueError("rmix 累计贡献筛选没有选出任何 CSF")
298
- return _unique_preserve_order(np.concatenate(mapped_by_block))
439
+ return selected
@@ -42,12 +42,20 @@ def validate_selection_idxs(
42
42
  duplicate values.
43
43
  """
44
44
  label = f" ({source})" if source is not None else ""
45
+ if row_count is not None and row_count < 0:
46
+ raise ValueError(f"row_count 不能为负数{label}")
45
47
  array = np.asarray(idxs)
46
48
  if array.ndim != 1:
47
49
  raise ValueError(f"选择索引必须是一维数组{label}: ndim={array.ndim}")
48
50
  if array.dtype.kind not in ("i", "u"):
49
51
  raise ValueError(f"选择索引必须是整数 dtype{label}: 实际 dtype={array.dtype}")
50
52
 
53
+ if (
54
+ array.size
55
+ and array.dtype.kind == "u"
56
+ and np.any(array > np.iinfo(np.int64).max)
57
+ ):
58
+ raise ValueError(f"选择索引超出 int64 范围{label}")
51
59
  int_array = array.astype(np.int64, copy=False)
52
60
  if int_array.size == 0:
53
61
  return int_array
@@ -199,8 +207,7 @@ def normalize_asf_row_indices(
199
207
  """Normalize and validate ASF matrix row indices for every rmix block."""
200
208
  if asf_row_indices is None:
201
209
  normalized_row_indices = [
202
- block.asf_row_indices.tolist()
203
- for block in asfs_mix_data.blocks
210
+ block.asf_row_indices.tolist() for block in asfs_mix_data.blocks
204
211
  ]
205
212
  else:
206
213
  normalized_row_indices = [
@@ -211,13 +218,13 @@ def normalize_asf_row_indices(
211
218
  "asf_row_indices 第一层长度与 mixing coefficient block 数量不一致"
212
219
  )
213
220
 
214
- for block, row_indices in zip(asfs_mix_data.blocks, normalized_row_indices, strict=True):
221
+ for block, row_indices in zip(
222
+ asfs_mix_data.blocks, normalized_row_indices, strict=True
223
+ ):
215
224
  if not row_indices:
216
225
  raise ValueError(f"Block {block.block_index}: asf_row_indices 不能为空")
217
226
  if len(row_indices) != len(set(row_indices)):
218
- raise ValueError(
219
- f"Block {block.block_index}: asf_row_indices 包含重复值"
220
- )
227
+ raise ValueError(f"Block {block.block_index}: asf_row_indices 包含重复值")
221
228
  if block.mix_coefficients.ndim != 2:
222
229
  raise ValueError(
223
230
  f"Block {block.block_index}: mixing coefficients 必须是二维矩阵"
@@ -116,9 +116,13 @@ class MixCoefLoader(BinaryFileLoader):
116
116
  if jblock != nb:
117
117
  raise ValueError(f"jblock ({jblock}) != nb ({nb})")
118
118
 
119
- if ncfblk < 1 or nevblk < 0 or iatjp < 1 or iaspa not in (1, 2):
119
+ if ncfblk < 1 or nevblk < 0 or iatjp < 1 or iaspa not in (-1, 1, 2):
120
120
  raise ValueError(f"Invalid mix coefficient block {nb} header")
121
121
 
122
+ # GRASP stores signed ISPAR (+1/-1). Keep the public Python
123
+ # convention (1=even, 2=odd), also accepting older Python files.
124
+ parity = 2 if iaspa == -1 else iaspa
125
+
122
126
  # GRASP omits all three data records when nevblk == 0.
123
127
  if nevblk:
124
128
  ivec: NDArray[np.int32] = self.read_fortran_record(
@@ -160,7 +164,7 @@ class MixCoefLoader(BinaryFileLoader):
160
164
  if (iatjp - 1) % 2 == 0
161
165
  else f"{iatjp - 1}/2"
162
166
  ),
163
- parity=iaspa,
167
+ parity=parity,
164
168
  level_ids=ivec_array.astype(np.int64, copy=False),
165
169
  base_energy=eav,
166
170
  level_energies=evals,
@@ -31,6 +31,7 @@ def write_mix_coefficient_block(
31
31
  As in rasfsplit, a block with no levels has no following data records.
32
32
  Uses native byte order, int32 record markers/integers, and float64 data,
33
33
  matching :class:`MixCoefLoader`. An existing output is overwritten.
34
+ Python parity (1=even, 2=odd) is written as GRASP ISPAR (+1/-1).
34
35
  """
35
36
  coefficient_count = block.csf_count * block.level_count
36
37
  counts = (
@@ -75,7 +76,7 @@ def write_mix_coefficient_block(
75
76
  block.csf_count,
76
77
  block.level_count,
77
78
  block.j_value_location,
78
- block.parity,
79
+ 1 if block.parity == 1 else -1,
79
80
  ],
80
81
  dtype=np.int32,
81
82
  ),
@@ -553,7 +553,7 @@ def iterative_levels_collection(
553
553
  energy_data = energy_data.join(
554
554
  temp_df.select(key_cols + cols_to_join),
555
555
  on=key_cols,
556
- how="outer",
556
+ how="full",
557
557
  coalesce=True,
558
558
  )
559
559
 
@@ -313,11 +313,20 @@ def filter_sorted_ci_scores_by_cumulative(
313
313
  if not 0 < cumulative_threshold <= 1:
314
314
  raise ValueError("cumulative_threshold must be > 0 and <= 1")
315
315
  score_array = _as_1d_score_array(sorted_scores, "sorted_scores")
316
+ if not np.isfinite(score_array).all() or np.any(score_array < 0):
317
+ raise ValueError("CI-square scores must be finite and non-negative")
316
318
  total = float(np.sum(score_array))
319
+ if not np.isfinite(total):
320
+ raise ValueError("CI-square total must be finite")
317
321
  if total <= 0:
318
322
  return np.array([], dtype=np.int64)
323
+ if cumulative_threshold == 1:
324
+ return np.flatnonzero(score_array > 0).astype(np.int64, copy=False)
319
325
  cumulative = np.cumsum(score_array) / total
320
- count = int(np.searchsorted(cumulative, cumulative_threshold, side="left")) + 1
326
+ count = min(
327
+ int(np.searchsorted(cumulative, cumulative_threshold, side="left")) + 1,
328
+ len(score_array),
329
+ )
321
330
  return np.arange(count, dtype=np.int64)
322
331
 
323
332
 
@@ -390,14 +399,14 @@ def load_rmix_ci_squared(
390
399
  0,
391
400
  mix_data.block_num,
392
401
  ):
393
- raise ValueError(
394
- "asf_row_indices length must match the number of rmix blocks"
395
- )
402
+ raise ValueError("asf_row_indices length must match the number of rmix blocks")
396
403
 
397
404
  selected_asf_rows: list[list[int]] = []
398
405
  ci_squared_list: list[NDArray[np.float64]] = []
399
406
  for block_index, block in enumerate(mix_data.blocks):
400
- coefficient_array = _as_1d_or_2d_float_array(block.mix_coefficients, "coefficients")
407
+ coefficient_array = _as_1d_or_2d_float_array(
408
+ block.mix_coefficients, "coefficients"
409
+ )
401
410
  block_asf_rows = (
402
411
  asf_row_indices[block_index]
403
412
  if asf_row_indices is not None and len(asf_row_indices) > 0
@@ -12,6 +12,7 @@ class MixCoefficientBlock:
12
12
  ``level_ids`` contains GRASP identifiers from ``ivec``. It is metadata,
13
13
  not a matrix index. Rows of ``level_energies`` and ``mix_coefficients``
14
14
  are addressed only by zero-based ``asf_row_indices``.
15
+ ``parity`` uses 1 for even and 2 for odd; binary I/O converts GRASP's +/-1.
15
16
  """
16
17
 
17
18
  block_index: int
@@ -1,3 +1,3 @@
1
1
  """Package version, also read by Hatchling when building distributions."""
2
2
 
3
- __version__ = "3.4.4"
3
+ __version__ = "3.5.2"
File without changes