graspkit-atomic 3.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of graspkit-atomic might be problematic. Click here for more details.

Files changed (43) hide show
  1. graspkit/CSFs_processor/__init__.py +56 -0
  2. graspkit/CSFs_processor/coupling.py +386 -0
  3. graspkit/CSFs_processor/extraction.py +129 -0
  4. graspkit/CSFs_processor/selection.py +298 -0
  5. graspkit/CSFs_processor/validation.py +230 -0
  6. graspkit/__init__.py +11 -0
  7. graspkit/data_IO/__init__.py +43 -0
  8. graspkit/data_IO/file_locator.py +135 -0
  9. graspkit/data_IO/loaders/__init__.py +31 -0
  10. graspkit/data_IO/loaders/base_loader.py +114 -0
  11. graspkit/data_IO/loaders/binary_file_loader.py +370 -0
  12. graspkit/data_IO/loaders/energy_file_loader.py +150 -0
  13. graspkit/data_IO/loaders/gj_factor_loader.py +185 -0
  14. graspkit/data_IO/loaders/hyperfine_structure_loader.py +217 -0
  15. graspkit/data_IO/loaders/lsj_comp_loader.py +259 -0
  16. graspkit/data_IO/loaders/mix_coef_loader.py +261 -0
  17. graspkit/data_IO/loaders/radial_analysis_loader.py +134 -0
  18. graspkit/data_IO/loaders/radial_wavefunction_loader.py +280 -0
  19. graspkit/data_IO/loaders/transition_loader.py +811 -0
  20. graspkit/data_IO/mix_coef_writer.py +90 -0
  21. graspkit/data_IO/produced_data_writor.py +129 -0
  22. graspkit/grasp_data_extractor/__init__.py +56 -0
  23. graspkit/grasp_data_extractor/asfs_data_processor.py +705 -0
  24. graspkit/grasp_data_extractor/radial_analysis.py +523 -0
  25. graspkit/grasp_data_extractor/radial_wavefunction_processor.py +71 -0
  26. graspkit/grasp_data_extractor/rmix_data_processor.py +422 -0
  27. graspkit/grasp_data_extractor/transition_data_processor.py +407 -0
  28. graspkit/py.typed +1 -0
  29. graspkit/utils/__init__.py +30 -0
  30. graspkit/utils/data_modules.py +105 -0
  31. graspkit/utils/environment_config.py +271 -0
  32. graspkit/utils/quadrupole_deformation.py +72 -0
  33. graspkit/utils/tool_function.py +91 -0
  34. graspkit/version.py +3 -0
  35. graspkit_atomic-3.4.1.dist-info/METADATA +167 -0
  36. graspkit_atomic-3.4.1.dist-info/RECORD +43 -0
  37. graspkit_atomic-3.4.1.dist-info/WHEEL +4 -0
  38. graspkit_atomic-3.4.1.dist-info/licenses/LICENSE +675 -0
  39. graspkit_plot/__init__.py +55 -0
  40. graspkit_plot/fig_settings.py +1286 -0
  41. graspkit_plot/mid_coupling.py +300 -0
  42. graspkit_plot/plot_functions.py +801 -0
  43. graspkit_plot/radial_analysis.py +180 -0
@@ -0,0 +1,56 @@
1
+ # -*- encoding: utf-8 -*-
2
+ """CSF parsing, coupling-J analysis, and deterministic selection algorithms."""
3
+
4
+ from .coupling import (
5
+ collect_coupling_groups,
6
+ select_csfs_by_coupling_theme,
7
+ summarize_coupling_ci_squared,
8
+ )
9
+ from .extraction import (
10
+ CsfDocument,
11
+ create_csf_document,
12
+ write_csf_documents,
13
+ )
14
+ from .selection import (
15
+ generate_unique_random_numbers,
16
+ random_choose_csfs,
17
+ rmix_cumulative_selected_row_idxs,
18
+ select_csf_indices_above_ci_squared_cutoff,
19
+ select_csf_indices_by_ci_squared_cutoff,
20
+ select_csfs_rows,
21
+ sort_csfs_by_mix_coefficient,
22
+ )
23
+ from .validation import (
24
+ load_selection_idxs,
25
+ validate_coupling_level,
26
+ validate_header_lines,
27
+ validate_headers_match,
28
+ validate_output_path_disjoint,
29
+ validate_selection_idxs,
30
+ )
31
+
32
+ __all__ = [
33
+ # coupling
34
+ "collect_coupling_groups",
35
+ "select_csfs_by_coupling_theme",
36
+ "summarize_coupling_ci_squared",
37
+ # selection
38
+ "select_csf_indices_above_ci_squared_cutoff",
39
+ "select_csf_indices_by_ci_squared_cutoff",
40
+ "sort_csfs_by_mix_coefficient",
41
+ "generate_unique_random_numbers",
42
+ "random_choose_csfs",
43
+ "select_csfs_rows",
44
+ "rmix_cumulative_selected_row_idxs",
45
+ # extraction
46
+ "CsfDocument",
47
+ "create_csf_document",
48
+ "write_csf_documents",
49
+ # validation
50
+ "validate_selection_idxs",
51
+ "load_selection_idxs",
52
+ "validate_header_lines",
53
+ "validate_headers_match",
54
+ "validate_output_path_disjoint",
55
+ "validate_coupling_level",
56
+ ]
@@ -0,0 +1,386 @@
1
+ # -*- encoding: utf-8 -*-
2
+ """Polars coupling-signature analysis for rCSFs DataFrames."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from fractions import Fraction
7
+
8
+ import numpy as np
9
+ from numpy.typing import NDArray
10
+ import polars as pl
11
+
12
+ from ..utils.data_modules import MixCoefficientData
13
+ from .validation import (
14
+ normalize_asf_row_indices,
15
+ validate_coupling_level,
16
+ )
17
+
18
+ _COUPLING_SIGNATURE_COLUMN = "coupling_signature"
19
+ _SELECTED_COUPLING_COLUMN = "_selected_coupling"
20
+
21
+
22
+ def _validate_coupling_frame(csfs_df: pl.DataFrame) -> None:
23
+ """Validate the rCSFs DataFrame contract used by coupling analysis."""
24
+ required_columns = {"idx", "block_id", _COUPLING_SIGNATURE_COLUMN}
25
+ missing_columns = required_columns.difference(csfs_df.columns)
26
+ if missing_columns:
27
+ missing = ", ".join(sorted(missing_columns))
28
+ raise ValueError(f"CSF DataFrame 缺少必要列: {missing}")
29
+
30
+ if csfs_df.schema[_COUPLING_SIGNATURE_COLUMN] != pl.List(pl.Int32):
31
+ raise ValueError("coupling_signature 必须是 Polars List(Int32) 列")
32
+ if not csfs_df.schema["block_id"].is_integer():
33
+ raise ValueError("block_id 必须是整数列")
34
+ if not csfs_df.schema["idx"].is_integer():
35
+ raise ValueError("idx 必须是整数列")
36
+ if csfs_df.is_empty():
37
+ raise ValueError("CSF DataFrame 不能为空")
38
+
39
+ for column in ("idx", "block_id", _COUPLING_SIGNATURE_COLUMN):
40
+ if csfs_df[column].null_count() != 0:
41
+ raise ValueError(f"{column} 不能包含 null")
42
+
43
+ has_empty_signature = bool(
44
+ csfs_df.select(pl.col(_COUPLING_SIGNATURE_COLUMN).list.len().eq(0).any()).item()
45
+ )
46
+ if has_empty_signature:
47
+ raise ValueError("coupling_signature 不能是空列表")
48
+
49
+ has_null_item = bool(
50
+ csfs_df.select(
51
+ pl.col(_COUPLING_SIGNATURE_COLUMN)
52
+ .list.eval(pl.element().is_null())
53
+ .list.any()
54
+ .any()
55
+ ).item()
56
+ )
57
+ if has_null_item:
58
+ raise ValueError("coupling_signature 不能包含 null 元素")
59
+
60
+
61
+ def _with_selected_coupling(
62
+ csfs_df: pl.DataFrame,
63
+ coupling_level: int | None,
64
+ ) -> pl.DataFrame:
65
+ """Add block-local row indices and the requested intermediate coupling."""
66
+ coupling_level = validate_coupling_level(coupling_level)
67
+ selected_coupling = pl.col(_COUPLING_SIGNATURE_COLUMN)
68
+ if coupling_level is not None:
69
+ intermediate_coupling = selected_coupling.list.slice(
70
+ 0,
71
+ selected_coupling.list.len() - 1,
72
+ )
73
+ selected_coupling = intermediate_coupling.list.tail(coupling_level)
74
+
75
+ return csfs_df.with_columns(
76
+ pl.int_range(pl.len(), dtype=pl.UInt64).over("block_id").alias("block_csf_idx"),
77
+ selected_coupling.alias(_SELECTED_COUPLING_COLUMN),
78
+ )
79
+
80
+
81
+ def collect_coupling_groups(
82
+ csfs_df: pl.DataFrame,
83
+ coupling_level: int | None = None,
84
+ ) -> pl.DataFrame:
85
+ """Group rCSFs coupling signatures with local and global CSF indices.
86
+
87
+ Args:
88
+ csfs_df: DataFrame returned by ``rcsfs.read_csfs`` with both
89
+ ``include_block_id`` and ``include_coupling_signature`` enabled.
90
+ coupling_level: Number of trailing intermediate-coupling ``2J`` values
91
+ used as the grouping pattern. The signature's final total J value
92
+ is excluded before counting. ``None`` retains the complete
93
+ signature, including total J.
94
+
95
+ Returns:
96
+ One row per block and coupling pattern with columns ``block_id``,
97
+ ``coupling_signature``, ``count``, block-local ``idxs``, and source
98
+ ``global_idxs``.
99
+
100
+ Raises:
101
+ ValueError: If the DataFrame does not satisfy the rCSFs column
102
+ contract or ``coupling_level`` is invalid.
103
+ """
104
+ _validate_coupling_frame(csfs_df)
105
+ annotated = _with_selected_coupling(csfs_df, coupling_level)
106
+
107
+ return (
108
+ annotated.group_by(
109
+ ["block_id", _SELECTED_COUPLING_COLUMN],
110
+ maintain_order=True,
111
+ )
112
+ .agg(
113
+ pl.len().alias("count"),
114
+ pl.col("block_csf_idx").alias("idxs"),
115
+ pl.col("idx").cast(pl.UInt64()).alias("global_idxs"),
116
+ )
117
+ .rename({_SELECTED_COUPLING_COLUMN: _COUPLING_SIGNATURE_COLUMN})
118
+ .select(
119
+ "block_id",
120
+ _COUPLING_SIGNATURE_COLUMN,
121
+ "count",
122
+ "idxs",
123
+ "global_idxs",
124
+ )
125
+ )
126
+
127
+
128
+ def _selected_block_coefficients(
129
+ csfs_df: pl.DataFrame,
130
+ asfs_mix_data: MixCoefficientData,
131
+ asf_row_indices: list[list[int]] | None,
132
+ ) -> list[tuple[int, list[int], NDArray[np.float64]]]:
133
+ """Validate J/CSF alignment and return selected ASF coefficient matrices."""
134
+ normalized_positions = normalize_asf_row_indices(
135
+ asfs_mix_data,
136
+ asf_row_indices,
137
+ )
138
+ dataframe_block_ids = (
139
+ csfs_df.get_column("block_id").unique(maintain_order=True).to_list()
140
+ )
141
+ mix_block_ids = [block.block_index for block in asfs_mix_data.blocks]
142
+ if dataframe_block_ids != mix_block_ids:
143
+ raise ValueError(
144
+ f"CSF block IDs {dataframe_block_ids} 与 rmix block IDs {mix_block_ids} 不一致"
145
+ )
146
+
147
+ selected_blocks: list[tuple[int, list[int], NDArray[np.float64]]] = []
148
+ for mix_block, mix_j_value, selected_positions in zip(
149
+ asfs_mix_data.blocks,
150
+ asfs_mix_data.level_J_value_list,
151
+ normalized_positions,
152
+ strict=True,
153
+ ):
154
+ coefficient_matrix = np.asarray(
155
+ mix_block.mix_coefficients,
156
+ dtype=np.float64,
157
+ )
158
+ if coefficient_matrix.ndim != 2:
159
+ raise ValueError(
160
+ f"Block {mix_block.block_index}: mixing coefficients 必须是二维矩阵"
161
+ )
162
+
163
+ dataframe_block = csfs_df.filter(
164
+ pl.col("block_id") == mix_block.block_index
165
+ )
166
+ dataframe_csf_count = dataframe_block.height
167
+ if coefficient_matrix.shape[1] != dataframe_csf_count:
168
+ raise ValueError(
169
+ f"Block {mix_block.block_index}: rmix CSF 数量 {coefficient_matrix.shape[1]} 与 CSF DataFrame {dataframe_csf_count} 不一致"
170
+ )
171
+
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
+ )
178
+ if len(csf_two_j_values) != 1:
179
+ raise ValueError(
180
+ f"Block {mix_block.block_index}: CSF DataFrame 包含多个总 J: 2J={csf_two_j_values}"
181
+ )
182
+ rmix_two_j = _twice_j_value(mix_j_value, block_index=mix_block.block_index)
183
+ csf_two_j = int(csf_two_j_values[0])
184
+ if csf_two_j != rmix_two_j:
185
+ raise ValueError(
186
+ f"Block {mix_block.block_index}: CSF J={_format_twice_j(csf_two_j)} 与 rmix J={mix_j_value} 不一致"
187
+ )
188
+
189
+ selected_blocks.append(
190
+ (
191
+ mix_block.block_index,
192
+ selected_positions,
193
+ coefficient_matrix[selected_positions],
194
+ )
195
+ )
196
+ return selected_blocks
197
+
198
+
199
+ def _twice_j_value(j_value: str, *, block_index: int) -> int:
200
+ """Convert an rmix integer or half-integer J label to integral ``2J``."""
201
+ try:
202
+ twice_j = Fraction(j_value) * 2
203
+ except (ValueError, ZeroDivisionError) as error:
204
+ raise ValueError(
205
+ f"Block {block_index}: rmix J 值格式无效: {j_value!r}"
206
+ ) from error
207
+ if twice_j.denominator != 1 or twice_j.numerator < 0:
208
+ raise ValueError(f"Block {block_index}: rmix J 值无效: {j_value!r}")
209
+ return twice_j.numerator
210
+
211
+
212
+ def _format_twice_j(two_j: int) -> str:
213
+ """Format integral ``2J`` using the same labels as MixCoefficientData."""
214
+ if two_j % 2 == 0:
215
+ return str(two_j // 2)
216
+ return f"{two_j}/2"
217
+
218
+
219
+ def _mixing_coefficients_to_long_frame(
220
+ csfs_df: pl.DataFrame,
221
+ asfs_mix_data: MixCoefficientData,
222
+ 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")
266
+
267
+
268
+ def summarize_coupling_ci_squared(
269
+ csfs_df: pl.DataFrame,
270
+ asfs_mix_data: MixCoefficientData,
271
+ asf_row_indices: list[list[int]] | None = None,
272
+ coupling_level: int | None = None,
273
+ ) -> pl.DataFrame:
274
+ """Summarize CI-square contributions by block, ASF, and coupling pattern.
275
+
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.
279
+ """
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(
288
+ csfs_df,
289
+ asfs_mix_data,
290
+ 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 未能完整对齐")
301
+
302
+ return (
303
+ joined.group_by(
304
+ ["block_id", "asf_index", _SELECTED_COUPLING_COLUMN],
305
+ maintain_order=True,
306
+ )
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"),
312
+ )
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",
322
+ )
323
+ )
324
+
325
+
326
+ def select_csfs_by_coupling_theme(
327
+ csfs_df: pl.DataFrame,
328
+ asfs_mix_data: MixCoefficientData,
329
+ *,
330
+ asf_row_indices: list[list[int]] | None = None,
331
+ ci_squared_cutoff: float,
332
+ coupling_level: int,
333
+ ) -> pl.DataFrame:
334
+ """Select rCSFs rows by CI-square threshold and dominant coupling theme.
335
+
336
+ The input must be returned by :func:`rcsfs.read_csfs` with both
337
+ ``include_block_id`` and ``include_coupling_signature`` enabled. For every
338
+ block, the result is the source-ordered union of CSFs whose selected-ASF
339
+ CI-square exceeds ``ci_squared_cutoff`` and every member of the dominant coupling
340
+ group for each selected ASF.
341
+
342
+ ``coupling_level`` is the positive number of trailing intermediate-coupling
343
+ integer ``2J`` values retained from the rCSFs fixed-width coupling
344
+ signature. The final total J value is excluded before counting.
345
+ """
346
+ validate_coupling_level(coupling_level)
347
+ if type(ci_squared_cutoff) not in (int, float):
348
+ raise ValueError("ci_squared_cutoff must be a finite non-negative number")
349
+ cutoff = float(ci_squared_cutoff)
350
+ if not np.isfinite(cutoff) or cutoff < 0:
351
+ raise ValueError("ci_squared_cutoff must be a finite non-negative number")
352
+
353
+ coupling_groups = collect_coupling_groups(csfs_df, coupling_level)
354
+ groups_by_block: dict[int, list[NDArray[np.int64]]] = {}
355
+ for block_id, idxs in coupling_groups.select("block_id", "idxs").iter_rows():
356
+ groups_by_block.setdefault(int(block_id), []).append(
357
+ np.asarray(idxs, dtype=np.int64)
358
+ )
359
+
360
+ block_ids = csfs_df.get_column("block_id").to_numpy()
361
+ selected_row_positions: list[int] = []
362
+ for block_id, _, selected_coefficients in _selected_block_coefficients(
363
+ csfs_df,
364
+ asfs_mix_data,
365
+ asf_row_indices,
366
+ ):
367
+ scores = np.square(selected_coefficients, dtype=np.float64)
368
+ block_groups = groups_by_block.get(block_id)
369
+ if not block_groups:
370
+ raise ValueError(f"CSF block {block_id} contains no coupling themes")
371
+
372
+ selected_local = set(
373
+ np.flatnonzero(np.any(scores > cutoff, axis=0)).astype(int).tolist()
374
+ )
375
+ group_sums = np.column_stack(
376
+ [np.sum(scores[:, idxs], axis=1) for idxs in block_groups]
377
+ )
378
+ for dominant_group_index in np.argmax(group_sums, axis=1):
379
+ selected_local.update(block_groups[int(dominant_group_index)].tolist())
380
+
381
+ block_row_positions = np.flatnonzero(block_ids == block_id)
382
+ selected_row_positions.extend(
383
+ block_row_positions[sorted(selected_local)].astype(int).tolist()
384
+ )
385
+
386
+ return csfs_df[np.asarray(sorted(selected_row_positions), dtype=np.int64)]
@@ -0,0 +1,129 @@
1
+ # -*- encoding: utf-8 -*-
2
+ """Config-free CSF extraction: select rows from a source and merge/write blocks."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ import polars as pl
11
+
12
+ from ..data_IO import write_csfs_blocks_to_cfile
13
+ from .validation import (
14
+ validate_header_lines,
15
+ validate_headers_match,
16
+ validate_output_path_disjoint,
17
+ )
18
+
19
+
20
+ _CSF_ROW_COLUMNS = ("line1", "line2", "line3")
21
+
22
+
23
+ def _validate_csf_frame(csfs_df: pl.DataFrame) -> None:
24
+ missing = set(_CSF_ROW_COLUMNS).difference(csfs_df.columns)
25
+ if missing:
26
+ raise ValueError(f"CSF DataFrame 缺少必要列: {', '.join(sorted(missing))}")
27
+ if csfs_df.is_empty():
28
+ raise ValueError("CSF DataFrame 不能为空")
29
+ for column in _CSF_ROW_COLUMNS:
30
+ if csfs_df.schema[column] != pl.String:
31
+ raise ValueError(f"{column} 必须是 Polars String 列")
32
+ if csfs_df[column].null_count() != 0:
33
+ raise ValueError(f"{column} 不能包含 null")
34
+ if "block_id" in csfs_df.columns:
35
+ if not csfs_df.schema["block_id"].is_integer():
36
+ raise ValueError("block_id 必须是整数列")
37
+ if csfs_df["block_id"].null_count() != 0:
38
+ raise ValueError("block_id 不能包含 null")
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class CsfDocument:
43
+ """Validated CSF rows and their shared five-line GRASP header.
44
+
45
+ Attributes:
46
+ header_lines: The 5-line GRASP header for ``csfs_df``'s source.
47
+ csfs_df: CSF rows; a ``block_id`` column may describe multiple blocks.
48
+ source_path: Path the rows were read from, used for path-conflict
49
+ checks when writing output.
50
+ label: Optional caller-supplied label (e.g. a J value) for
51
+ diagnostics.
52
+ """
53
+
54
+ header_lines: tuple[str, str, str, str, str]
55
+ csfs_df: pl.DataFrame
56
+ source_path: Path
57
+ label: str | None = None
58
+
59
+ def __post_init__(self) -> None:
60
+ validated_header = validate_header_lines(self.header_lines)
61
+ object.__setattr__(self, "header_lines", tuple(validated_header))
62
+ _validate_csf_frame(self.csfs_df)
63
+
64
+ def blocks(self) -> list[pl.DataFrame]:
65
+ """Return source-ordered frames ready for GRASP block writing."""
66
+ if "block_id" not in self.csfs_df.columns:
67
+ return [self.csfs_df]
68
+ return self.csfs_df.partition_by("block_id", maintain_order=True)
69
+
70
+
71
+ def create_csf_document(
72
+ *,
73
+ header_lines: Sequence[str],
74
+ csfs_df: pl.DataFrame,
75
+ source_path: Path,
76
+ label: str | None = None,
77
+ ) -> CsfDocument:
78
+ """Create the unified CSF document used across selection workflows."""
79
+ validated_header = validate_header_lines(header_lines)
80
+ return CsfDocument(
81
+ header_lines=(
82
+ validated_header[0],
83
+ validated_header[1],
84
+ validated_header[2],
85
+ validated_header[3],
86
+ validated_header[4],
87
+ ),
88
+ csfs_df=csfs_df,
89
+ source_path=source_path,
90
+ label=label,
91
+ )
92
+
93
+
94
+ def write_csf_documents(
95
+ documents: Sequence[CsfDocument],
96
+ output_file: Path,
97
+ *,
98
+ extra_input_paths: Sequence[Path | None] = (),
99
+ ) -> None:
100
+ """Validate header/path consistency, then atomically write merged CSFs.
101
+
102
+ Args:
103
+ documents: CSF documents to merge in source and block order.
104
+ output_file: Destination ``.c`` file.
105
+ extra_input_paths: Additional input paths (e.g. idx files) that must
106
+ not collide with ``output_file``, beyond each block's
107
+ ``source_path``.
108
+
109
+ Raises:
110
+ ValueError: If ``blocks`` is empty, headers across blocks differ, or
111
+ ``output_file`` collides with any input path.
112
+ """
113
+ if not documents:
114
+ raise ValueError("没有可写入的 CSFs block")
115
+
116
+ header_lines = validate_headers_match(
117
+ [document.header_lines for document in documents],
118
+ labels=[document.label for document in documents],
119
+ )
120
+ validate_output_path_disjoint(
121
+ output_file,
122
+ [*(document.source_path for document in documents), *extra_input_paths],
123
+ )
124
+
125
+ write_csfs_blocks_to_cfile(
126
+ header_lines,
127
+ [block for document in documents for block in document.blocks()],
128
+ output_file,
129
+ )