graspkit-atomic 3.4.3__tar.gz → 3.4.4__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 (50) hide show
  1. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/INSTALL.md +4 -4
  2. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/PKG-INFO +3 -3
  3. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/README.md +2 -2
  4. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/README_zh.md +2 -2
  5. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/docs/releasing.md +15 -6
  6. graspkit_atomic-3.4.4/src/graspkit/CSFs_processor/mr_selection.py +391 -0
  7. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/mix_coef_loader.py +14 -2
  8. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/version.py +1 -1
  9. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/.gitignore +0 -0
  10. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/LICENSE +0 -0
  11. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/build_package.py +0 -0
  12. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/pyproject.toml +0 -0
  13. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/scripts/check_release.py +0 -0
  14. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/CSFs_processor/__init__.py +0 -0
  15. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/CSFs_processor/coupling.py +0 -0
  16. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/CSFs_processor/extraction.py +0 -0
  17. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/CSFs_processor/selection.py +0 -0
  18. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/CSFs_processor/validation.py +0 -0
  19. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/__init__.py +0 -0
  20. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/__init__.py +0 -0
  21. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/file_locator.py +0 -0
  22. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/__init__.py +0 -0
  23. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/base_loader.py +0 -0
  24. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/binary_file_loader.py +0 -0
  25. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/energy_file_loader.py +0 -0
  26. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/gj_factor_loader.py +0 -0
  27. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/hyperfine_structure_loader.py +0 -0
  28. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/lsj_comp_loader.py +0 -0
  29. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/radial_analysis_loader.py +0 -0
  30. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/radial_wavefunction_loader.py +0 -0
  31. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/loaders/transition_loader.py +0 -0
  32. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/mix_coef_writer.py +0 -0
  33. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/data_IO/produced_data_writor.py +0 -0
  34. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/__init__.py +0 -0
  35. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/asfs_data_processor.py +0 -0
  36. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/radial_analysis.py +0 -0
  37. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/radial_wavefunction_processor.py +0 -0
  38. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/rmix_data_processor.py +0 -0
  39. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/grasp_data_extractor/transition_data_processor.py +0 -0
  40. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/py.typed +0 -0
  41. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/utils/__init__.py +0 -0
  42. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/utils/data_modules.py +0 -0
  43. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/utils/environment_config.py +0 -0
  44. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/utils/quadrupole_deformation.py +0 -0
  45. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit/utils/tool_function.py +0 -0
  46. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit_plot/__init__.py +0 -0
  47. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit_plot/fig_settings.py +0 -0
  48. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit_plot/mid_coupling.py +0 -0
  49. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit_plot/plot_functions.py +0 -0
  50. {graspkit_atomic-3.4.3 → graspkit_atomic-3.4.4}/src/graspkit_plot/radial_analysis.py +0 -0
@@ -15,12 +15,12 @@ python -m pip install graspkit-atomic
15
15
  For a fixed release:
16
16
 
17
17
  ```bash
18
- python -m pip install "graspkit-atomic==3.4.3"
18
+ python -m pip install "graspkit-atomic==3.4.4"
19
19
  ```
20
20
 
21
21
  ## Declare a project dependency
22
22
 
23
- Add `"graspkit-atomic==3.4.3"` to the existing `[project].dependencies` list in
23
+ Add `"graspkit-atomic==3.4.4"` to the existing `[project].dependencies` list in
24
24
  your own `pyproject.toml`. A minimal example:
25
25
 
26
26
  ```toml
@@ -28,7 +28,7 @@ your own `pyproject.toml`. A minimal example:
28
28
  name = "atomic-analysis"
29
29
  version = "0.1.0"
30
30
  requires-python = ">=3.14"
31
- dependencies = ["graspkit-atomic==3.4.3"]
31
+ dependencies = ["graspkit-atomic==3.4.4"]
32
32
  ```
33
33
 
34
34
  For a uv-managed project, run `uv sync` after editing `pyproject.toml`, then
@@ -47,7 +47,7 @@ requires the corresponding GRASP data files.
47
47
  To install a downloaded wheel, use its exact filename:
48
48
 
49
49
  ```bash
50
- python -m pip install /path/to/graspkit_atomic-3.4.3-py3-none-any.whl
50
+ python -m pip install /path/to/graspkit_atomic-3.4.4-py3-none-any.whl
51
51
  ```
52
52
 
53
53
  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.3
3
+ Version: 3.4.4
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
@@ -85,7 +85,7 @@ For an existing uv project using Python 3.14 or newer, run `uv add graspkit-atom
85
85
  in its directory. This records the dependency in `pyproject.toml`, updates
86
86
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
87
87
  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.3"`.
88
+ To pin a particular release, use `uv add "graspkit-atomic==3.4.4"`.
89
89
 
90
90
  You can also add the dependency to an existing `pyproject.toml` manually:
91
91
 
@@ -95,7 +95,7 @@ name = "atomic-analysis"
95
95
  version = "0.1.0"
96
96
  requires-python = ">=3.14"
97
97
  dependencies = [
98
- "graspkit-atomic==3.4.3",
98
+ "graspkit-atomic==3.4.4",
99
99
  ]
100
100
  ```
101
101
 
@@ -38,7 +38,7 @@ For an existing uv project using Python 3.14 or newer, run `uv add graspkit-atom
38
38
  in its directory. This records the dependency in `pyproject.toml`, updates
39
39
  `uv.lock`, and installs it in the project's `.venv`. Use `uv run python analysis.py`
40
40
  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.3"`.
41
+ To pin a particular release, use `uv add "graspkit-atomic==3.4.4"`.
42
42
 
43
43
  You can also add the dependency to an existing `pyproject.toml` manually:
44
44
 
@@ -48,7 +48,7 @@ name = "atomic-analysis"
48
48
  version = "0.1.0"
49
49
  requires-python = ">=3.14"
50
50
  dependencies = [
51
- "graspkit-atomic==3.4.3",
51
+ "graspkit-atomic==3.4.4",
52
52
  ]
53
53
  ```
54
54
 
@@ -31,7 +31,7 @@ uv run python -c "import graspkit; print(graspkit.__version__)"
31
31
  已有 uv 项目使用 Python 3.14 或更新版本时,直接在其目录运行 `uv add graspkit-atomic`。
32
32
  该命令会将依赖写入 `pyproject.toml`,更新 `uv.lock`,并安装到项目的 `.venv` 中。
33
33
  运行自己的分析脚本时使用 `uv run python analysis.py`,无需手动激活环境。
34
- 需要固定版本时,使用 `uv add "graspkit-atomic==3.4.3"`。
34
+ 需要固定版本时,使用 `uv add "graspkit-atomic==3.4.4"`。
35
35
 
36
36
  也可以手动将依赖加入已有的 `pyproject.toml`:
37
37
 
@@ -41,7 +41,7 @@ name = "atomic-analysis"
41
41
  version = "0.1.0"
42
42
  requires-python = ">=3.14"
43
43
  dependencies = [
44
- "graspkit-atomic==3.4.3",
44
+ "graspkit-atomic==3.4.4",
45
45
  ]
46
46
  ```
47
47
 
@@ -1,10 +1,19 @@
1
1
  # Preparing a graspkit-atomic release
2
2
 
3
- The prepared stable version is **3.4.3**. Its single source is
3
+ The prepared stable version is **3.4.4**. Its single source is
4
4
  `src/graspkit/version.py`; Hatchling reads it through `dynamic = ["version"]`.
5
5
  The local build commands below do not upload files or create Git tags.
6
6
  The separate manual publishing workflow is described near the end of this guide.
7
7
 
8
+ ## Changes in 3.4.4
9
+
10
+ - Add exact jj-CSF MR selection with original level-ID mapping, strict amplitude
11
+ or squared-weight cutoffs, per-ASF unions, and source-indexed audit results.
12
+ - Validate CSF/mixing structure, finite coefficients and target norms before
13
+ selection; keep configuration-family summaries separate from selected records.
14
+ - Reject mixing files with inconsistent header totals, nonpositive level IDs,
15
+ or unexpected trailing data.
16
+
8
17
  ## Local build in the paired workspace
9
18
 
10
19
  Set up or refresh the shared environment from `graspkit-tools/` with
@@ -23,8 +32,8 @@ The obsolete `--dev` option is removed; edit the version source deliberately.
23
32
  `--clean` removes only matching graspkit-atomic archives from the selected output
24
33
  folder. Unknown files cause an error instead of being deleted.
25
34
 
26
- Output: `dist/graspkit_atomic-3.4.3.tar.gz` and
27
- `dist/graspkit_atomic-3.4.3-py3-none-any.whl`. An optional `--outdir PATH` selects an
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
28
37
  empty output folder. The shell/batch wrappers select the shared Tools Python.
29
38
 
30
39
  Equivalent individual checks:
@@ -79,7 +88,7 @@ with a branch selector. Review all three platform jobs before using the artifact
79
88
  ## Before a later publication
80
89
 
81
90
  1. Review the exact source commit and release changes; rerun the workflow on it.
82
- 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.4.3
91
+ 2. Confirm PyPI ownership/availability of `graspkit-atomic`, and that version 3.4.4
83
92
  has not already been published. A missing public project page alone does
84
93
  not prove that a name is available.
85
94
  3. Inspect the actual archives and hashes. Publishing makes their contents
@@ -103,7 +112,7 @@ completing a build does not start a publication. Its inputs are:
103
112
 
104
113
  | Input | Default | Purpose |
105
114
  | --- | --- | --- |
106
- | `version` | Required | Exact source version, currently `3.4.3`. |
115
+ | `version` | Required | Exact source version, currently `3.4.4`. |
107
116
  | `publish_pypi` | Off | Upload the validated packages to PyPI. |
108
117
  | `github_release` | Off | Create a GitHub Release using the same packages. |
109
118
  | `draft` | On | Keep the GitHub Release as a draft; turn off only for formal publication. |
@@ -119,7 +128,7 @@ source version, and select the destinations you intend to use:
119
128
  | On | On | Build and validate once, then upload the same files to both destinations. |
120
129
 
121
130
  A prior dry run is optional. No separate workflow, run ID or tag input is
122
- needed. The GitHub tag is derived as `v{version}`, for example `v3.4.3`.
131
+ needed. The GitHub tag is derived as `v{version}`, for example `v3.4.4`.
123
132
  The `draft` option has no effect when `github_release` is off.
124
133
 
125
134
  ### One build, two independent destinations
@@ -0,0 +1,391 @@
1
+ """Exact jj-CSF MR selection, independent of CLI and CSF reader backends.
2
+
3
+ Targets use zero-based block indices and the loader's ``ivec - 1`` level IDs.
4
+ The caller supplies an in-memory document read without truncation, and remains
5
+ responsible for file snapshots/provenance. Structural agreement cannot establish
6
+ historical pairing: legacy mixing files contain no CSF-content digest.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass
13
+ from fractions import Fraction
14
+ import math
15
+ import re
16
+ from typing import cast
17
+
18
+ import numpy as np
19
+ from numpy.typing import NDArray
20
+
21
+ from ..utils.data_modules import MixCoefficientData
22
+ from .extraction import CsfDocument, create_csf_document
23
+ from .selection import select_csf_indices_by_ci_squared_cutoff
24
+
25
+ # GRASP orbital lettering omits j. This parses occupation metadata only; the
26
+ # original coupling records are never reconstructed from these labels.
27
+ _LETTERS = "spdfghiklmnoqrtuvwxyz"
28
+ _ORBITAL = re.compile(r"([1-9]\d*)([" + _LETTERS + r"])(-?)")
29
+ _OCCUPATION = re.compile(r"([1-9]\d*[" + _LETTERS + r"]-?)\s*\(\s*(\d+)\)")
30
+ _TOTAL_J = re.compile(r"(?:^|\s)(\d+(?:/2)?)\s*([+-])\s*$")
31
+ NORM_TOLERANCE = 1e-8
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class MrTarget:
36
+ """A source block index and loader level ID, both zero-based."""
37
+
38
+ block_index: int
39
+ level_id: int
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class MrSelection:
44
+ """Selected original records and source-indexed, JSON-compatible audit rows."""
45
+
46
+ document: CsfDocument
47
+ selected_rows: list[dict[str, object]]
48
+ configuration_families: list[dict[str, object]]
49
+ target_summaries: list[dict[str, object]]
50
+ block_mapping: list[dict[str, int]]
51
+ cutoff_mode: str
52
+ cutoff: float
53
+ omitted_core_subshells: tuple[str, ...]
54
+ source_csf_count: int
55
+
56
+ def summary(self) -> dict[str, object]:
57
+ """Return numerical checks and index conventions for an audit manifest."""
58
+ source_records = {
59
+ int(cast(int, row["source_row_index_0based"])): {
60
+ name: row[name]
61
+ for name in (
62
+ "source_block_1based",
63
+ "output_block_1based",
64
+ "csf_index_in_block_1based",
65
+ "source_row_index_0based",
66
+ )
67
+ }
68
+ for row in self.selected_rows
69
+ }
70
+ return {
71
+ "threshold": {
72
+ "mode": self.cutoff_mode,
73
+ "value": self.cutoff,
74
+ "comparison": ">",
75
+ },
76
+ "source_csf_count": self.source_csf_count,
77
+ "selected_csf_count": self.document.csfs_df.height,
78
+ "selected_family_count": len(
79
+ {row["configuration_family"] for row in self.configuration_families}
80
+ ),
81
+ "targets": self.target_summaries,
82
+ "block_mapping": self.block_mapping,
83
+ "selected_source_records": [
84
+ source_records[index] for index in sorted(source_records)
85
+ ],
86
+ "omitted_closed_core_subshells": list(self.omitted_core_subshells),
87
+ "family_definition": "Sum jj subshell occupations at fixed n,l; omit only header core. Reporting only, not a coupling specification.",
88
+ "checks": {
89
+ "block_dimensions_and_order": "passed",
90
+ "j_parity_all_records": "passed",
91
+ "electrons_all_records": "passed",
92
+ "header_orbital_count": "passed",
93
+ "coefficients_finite": "passed",
94
+ "target_norms": "passed",
95
+ "norm_absolute_tolerance": NORM_TOLERANCE,
96
+ },
97
+ "index_conventions": {
98
+ "source_block_1based": "original file block order",
99
+ "level_id_1based": "original GRASP ivec, not matrix row",
100
+ "asf_row_index_0based": "resolved using row_for_level_id(ivec - 1)",
101
+ "source_row_index_0based": "sum of preceding source block lengths plus local index; ignores dataframe idx",
102
+ "csf_index_in_block_1based": "original CSF position in source block",
103
+ },
104
+ "interpretation": "Weights describe the original expansion, not a re-solved wavefunction or an energy/HFS/isotope-shift error bound.",
105
+ }
106
+
107
+
108
+ def _orbital_capacity(label: str) -> int:
109
+ match = _ORBITAL.fullmatch(label)
110
+ if match is None:
111
+ raise ValueError(f"Invalid relativistic subshell: {label!r}")
112
+ angular = _LETTERS.index(match[2])
113
+ if int(match[1]) <= angular or (angular == 0 and match[3]):
114
+ raise ValueError(f"Invalid relativistic subshell: {label!r}")
115
+ return 2 * angular if match[3] else 2 * angular + 2
116
+
117
+
118
+ def _occupations(line: str, peel: set[str]) -> dict[str, int]:
119
+ matches = list(_OCCUPATION.finditer(line))
120
+ if not matches or _OCCUPATION.sub("", line).strip():
121
+ raise ValueError(f"Malformed CSF occupation line: {line!r}")
122
+ occupations: dict[str, int] = {}
123
+ for match in matches:
124
+ label, count = match[1], int(match[2])
125
+ if label not in peel or label in occupations:
126
+ raise ValueError(f"Unknown or duplicate peel subshell: {label}")
127
+ if not 1 <= count <= _orbital_capacity(label):
128
+ raise ValueError(f"Invalid occupation for {label}: {count}")
129
+ occupations[label] = count
130
+ return occupations
131
+
132
+
133
+ def _family(occupations: dict[str, int]) -> str:
134
+ merged: dict[str, int] = {}
135
+ for label, count in occupations.items():
136
+ nonrelativistic = label.rstrip("-")
137
+ merged[nonrelativistic] = merged.get(nonrelativistic, 0) + count
138
+ labels = sorted(
139
+ merged, key=lambda label: (int(label[:-1]), _LETTERS.index(label[-1]))
140
+ )
141
+ return " ".join(f"{label}({merged[label]})" for label in labels)
142
+
143
+
144
+ def _validate_pair(
145
+ document: CsfDocument, block_lengths: Sequence[int], mixing: MixCoefficientData
146
+ ) -> list[str]:
147
+ frame = document.csfs_df
148
+ if list(block_lengths) != [block.csf_count for block in mixing.blocks]:
149
+ raise ValueError("CSF/mixing block dimensions disagree")
150
+ if sum(block_lengths) != frame.height or "block_id" not in frame.columns:
151
+ raise ValueError("CSF row count or block_id missing/inconsistent")
152
+ if [document.header_lines[i].strip() for i in (0, 2, 4)] != [
153
+ "Core subshells:",
154
+ "Peel subshells:",
155
+ "CSF(s):",
156
+ ]:
157
+ raise ValueError("Invalid CSF header labels")
158
+ core = document.header_lines[1].split()
159
+ peel = document.header_lines[3].split()
160
+ peel_set = set(peel)
161
+ orbitals = core + peel
162
+ if len(set(orbitals)) != len(orbitals):
163
+ raise ValueError("Duplicate subshell in CSF header")
164
+ core_electrons = sum(_orbital_capacity(label) for label in core)
165
+ for label in peel:
166
+ _orbital_capacity(label)
167
+ if mixing.orbital_count != len(orbitals):
168
+ raise ValueError("CSF header/mixing orbital count mismatch")
169
+ families: list[str] = []
170
+ offset = 0
171
+ for block_index, block in enumerate(mixing.blocks):
172
+ if block.block_index != block_index:
173
+ raise ValueError("Mixing block order mismatch")
174
+ if np.any(block.level_ids < 0):
175
+ raise ValueError("Negative loader level ID")
176
+ if not np.all(np.isfinite(block.mix_coefficients)):
177
+ raise ValueError("Non-finite mixing coefficient")
178
+ if not math.isfinite(block.base_energy) or not np.all(
179
+ np.isfinite(block.level_energies)
180
+ ):
181
+ raise ValueError("Non-finite mixing energy")
182
+ rows = cast(
183
+ list[tuple[int, str, str]],
184
+ frame.slice(offset, block.csf_count)
185
+ .select("block_id", "line1", "line3")
186
+ .rows(),
187
+ )
188
+ for source_block, line1, line3 in rows:
189
+ if source_block != block_index:
190
+ raise ValueError("CSF block_id disagrees with source block offsets")
191
+ occupations = _occupations(line1, peel_set)
192
+ if core_electrons + sum(occupations.values()) != mixing.electron_count:
193
+ raise ValueError("CSF/mixing electron count mismatch")
194
+ match = _TOTAL_J.search(line3)
195
+ if match is None:
196
+ raise ValueError(f"Missing total J/parity in coupling line: {line3!r}")
197
+ two_j = 2 * Fraction(match[1])
198
+ parity = 1 if match[2] == "+" else 2
199
+ occupation_parity = (
200
+ sum(
201
+ _LETTERS.index(label.rstrip("-")[-1]) * count
202
+ for label, count in occupations.items()
203
+ )
204
+ % 2
205
+ + 1
206
+ )
207
+ if (
208
+ two_j != block.j_value_location - 1
209
+ or parity != block.parity
210
+ or parity != occupation_parity
211
+ ):
212
+ raise ValueError("CSF/mixing J/parity mismatch")
213
+ families.append(_family(occupations))
214
+ offset += block.csf_count
215
+ return families
216
+
217
+
218
+ def select_mr_csfs(
219
+ document: CsfDocument,
220
+ block_lengths: Sequence[int],
221
+ mixing: MixCoefficientData,
222
+ targets: Sequence[MrTarget],
223
+ *,
224
+ amplitude_cutoff: float | None = None,
225
+ weight_cutoff: float | None = None,
226
+ ) -> MrSelection:
227
+ """Validate pairing structurally and select the per-target strict-cutoff union.
228
+
229
+ No normalization, cumulative weighting, configuration expansion, file writes
230
+ or physical convergence claims are performed. Requested empty blocks fail.
231
+ The document must come from a strict, non-truncating reader.
232
+ """
233
+ if (amplitude_cutoff is None) == (weight_cutoff is None):
234
+ raise ValueError("Specify exactly one amplitude_cutoff or weight_cutoff")
235
+ cutoff = (
236
+ amplitude_cutoff if amplitude_cutoff is not None else cast(float, weight_cutoff)
237
+ )
238
+ if not math.isfinite(cutoff) or not 0 <= cutoff < 1:
239
+ raise ValueError("Cutoff must be finite and within [0, 1)")
240
+ if not targets or len(set(targets)) != len(targets):
241
+ raise ValueError("Targets must be nonempty and unique")
242
+ requested: dict[int, list[int]] = {}
243
+ for target in targets:
244
+ if (
245
+ type(target.block_index) is not int
246
+ or type(target.level_id) is not int
247
+ or target.level_id < 0
248
+ or not 0 <= target.block_index < mixing.block_num
249
+ ):
250
+ raise ValueError(f"Invalid target: {target}")
251
+ block = mixing.blocks[target.block_index]
252
+ row = block.row_for_level_id(target.level_id)
253
+ requested.setdefault(target.block_index, []).append(row)
254
+ families = _validate_pair(document, block_lengths, mixing)
255
+ source_records = document.csfs_df.select("line1", "line2", "line3")
256
+ selected_global: list[int] = []
257
+ selected_rows: list[dict[str, object]] = []
258
+ family_rows: list[dict[str, object]] = []
259
+ summaries: list[dict[str, object]] = []
260
+ mapping: list[dict[str, int]] = []
261
+ offset = 0
262
+ for block in mixing.blocks:
263
+ block_index = block.block_index
264
+ if block_index not in requested:
265
+ offset += block.csf_count
266
+ continue
267
+ rows = requested[block_index]
268
+ coefficients = block.mix_coefficients[rows]
269
+ squared = np.square(coefficients)
270
+ norms = np.sum(squared, axis=1)
271
+ if np.any(np.abs(norms - 1.0) > NORM_TOLERANCE):
272
+ raise ValueError(
273
+ f"Block {block_index + 1}: target ASF norm differs from 1 by more than {NORM_TOLERANCE}"
274
+ )
275
+ triggered = (
276
+ (np.abs(coefficients) > cutoff)
277
+ if amplitude_cutoff is not None
278
+ else (squared > cutoff)
279
+ )
280
+ selected: NDArray[np.int64]
281
+ if weight_cutoff is not None:
282
+ selected = select_csf_indices_by_ci_squared_cutoff(
283
+ MixCoefficientData(blocks=[block], sorted_level_energies=[]),
284
+ asf_row_indices=[rows],
285
+ ci_squared_cutoff=cutoff,
286
+ )[block_index]
287
+ else:
288
+ selected = np.flatnonzero(np.any(triggered, axis=0)).astype(np.int64)
289
+ if selected.size == 0:
290
+ raise ValueError(f"Block {block_index + 1}: empty selection")
291
+ output_block = len(mapping) + 1
292
+ mapping.append(
293
+ {
294
+ "source_block_1based": block_index + 1,
295
+ "output_block_1based": output_block,
296
+ "source_csf_count": block.csf_count,
297
+ "selected_csf_count": int(selected.size),
298
+ }
299
+ )
300
+ selected_global.extend(offset + int(index) for index in selected)
301
+ block_families = families[offset : offset + block.csf_count]
302
+ family_all: dict[str, list[int]] = {}
303
+ family_kept: dict[str, list[int]] = {}
304
+ for index, family in enumerate(block_families):
305
+ family_all.setdefault(family, []).append(index)
306
+ for index in selected:
307
+ local = int(index)
308
+ family_kept.setdefault(block_families[local], []).append(local)
309
+ for position, row in enumerate(rows):
310
+ level = int(block.level_ids[row]) + 1
311
+ identity: dict[str, object] = {
312
+ "source_block_1based": block_index + 1,
313
+ "output_block_1based": output_block,
314
+ "level_id_1based": level,
315
+ "loader_level_id_0based": level - 1,
316
+ "asf_row_index_0based": row,
317
+ "j": block.j_value,
318
+ "parity": "+" if block.parity == 1 else "-",
319
+ }
320
+ kept = float(squared[position, selected].sum())
321
+ summaries.append(
322
+ {
323
+ **identity,
324
+ "energy_hartree": float(
325
+ block.base_energy + block.level_energies[row]
326
+ ),
327
+ "weight_all": float(norms[position]),
328
+ "triggered_csf_count": int(triggered[position].sum()),
329
+ "weight_triggered": float(
330
+ squared[position, triggered[position]].sum()
331
+ ),
332
+ "weight_kept": kept,
333
+ "weight_omitted": float(norms[position]) - kept,
334
+ }
335
+ )
336
+ for index in selected:
337
+ local = int(index)
338
+ source = offset + local
339
+ record = cast(
340
+ tuple[str, str, str],
341
+ source_records.row(source),
342
+ )
343
+ selected_rows.append(
344
+ {
345
+ **identity,
346
+ "csf_index_in_block_1based": local + 1,
347
+ "source_row_index_0based": source,
348
+ "coefficient": float(coefficients[position, local]),
349
+ "squared_weight": float(squared[position, local]),
350
+ "triggered_selection": bool(triggered[position, local]),
351
+ "triggering_level_ids_1based": ";".join(
352
+ str(int(block.level_ids[rows[p]]) + 1)
353
+ for p in range(len(rows))
354
+ if triggered[p, local]
355
+ ),
356
+ "configuration_family": block_families[local],
357
+ **dict(zip(("line1", "line2", "line3"), record, strict=True)),
358
+ }
359
+ )
360
+ for family, kept_indices in family_kept.items():
361
+ all_indices = family_all[family]
362
+ family_rows.append(
363
+ {
364
+ **identity,
365
+ "configuration_family": family,
366
+ "source_csf_count": len(all_indices),
367
+ "selected_csf_count": len(kept_indices),
368
+ "family_weight_all": float(
369
+ squared[position, all_indices].sum()
370
+ ),
371
+ "family_weight_selected": float(
372
+ squared[position, kept_indices].sum()
373
+ ),
374
+ }
375
+ )
376
+ offset += block.csf_count
377
+ return MrSelection(
378
+ document=create_csf_document(
379
+ header_lines=document.header_lines,
380
+ csfs_df=document.csfs_df[selected_global],
381
+ source_path=document.source_path,
382
+ ),
383
+ selected_rows=selected_rows,
384
+ configuration_families=family_rows,
385
+ target_summaries=summaries,
386
+ block_mapping=mapping,
387
+ cutoff_mode="amplitude" if amplitude_cutoff is not None else "squared_weight",
388
+ cutoff=cutoff,
389
+ omitted_core_subshells=tuple(document.header_lines[1].split()),
390
+ source_csf_count=document.csfs_df.height,
391
+ )
@@ -89,14 +89,14 @@ class MixCoefLoader(BinaryFileLoader):
89
89
  # READ (nfmix) nelec, ncftot, nw, nvectot, nvecsiz, nblock
90
90
  # nelec -> num_electron, ncftot -> total_num_configuration,
91
91
  # nw -> nw, ncmin -> ncmin, nvecsiz -> nvecsiz, nblock -> num_block
92
- nelec, _ncftot, nw, _ncmin, _nvecsiz, nblock = tuple[int, ...](
92
+ nelec, ncftot, nw, ncmin, nvecsiz, nblock = tuple[int, ...](
93
93
  int(x)
94
94
  for x in self.read_mixed_scalars(
95
95
  file=binary_file, field_specs=["i", "i", "i", "i", "i", "i"]
96
96
  )
97
97
  )
98
98
 
99
- if nelec < 0 or nw < 0 or nblock < 0:
99
+ if min(nelec, ncftot, nw, ncmin, nvecsiz, nblock) < 0:
100
100
  raise ValueError("Negative count in mix coefficient file header")
101
101
 
102
102
  blocks: list[MixCoefficientBlock] = []
@@ -125,6 +125,8 @@ class MixCoefLoader(BinaryFileLoader):
125
125
  file=binary_file, dtype="int32", count=nevblk
126
126
  )
127
127
  ivec_array = ivec.astype(np.int64) - 1
128
+ if np.any(ivec_array < 0):
129
+ raise ValueError("GRASP level IDs must be positive")
128
130
  eva_evals: NDArray[np.float64] = self.read_fortran_record(
129
131
  file=binary_file, dtype="float64", count=nevblk + 1
130
132
  )
@@ -166,6 +168,16 @@ class MixCoefLoader(BinaryFileLoader):
166
168
  )
167
169
  )
168
170
 
171
+ if (
172
+ sum(block.csf_count for block in blocks) != ncftot
173
+ or sum(block.level_count for block in blocks) != ncmin
174
+ or sum(block.csf_count * block.level_count for block in blocks)
175
+ != nvecsiz
176
+ ):
177
+ raise ValueError("Mix header totals disagree with block dimensions")
178
+ if binary_file.read(1):
179
+ raise ValueError("Unexpected trailing data in mix coefficient file")
180
+
169
181
  # 收集能级能量
170
182
  temp_energy = _collect_level_metadata(blocks)[3]
171
183
 
@@ -1,3 +1,3 @@
1
1
  """Package version, also read by Hatchling when building distributions."""
2
2
 
3
- __version__ = "3.4.3"
3
+ __version__ = "3.4.4"
File without changes