Skip to content

refactor(synthetic): move generation out of eval - #329

Merged
xraymemory merged 4 commits into
mainfrom
xraymemory/issue-312-move-synthetic
Jul 22, 2026
Merged

refactor(synthetic): move generation out of eval#329
xraymemory merged 4 commits into
mainfrom
xraymemory/issue-312-move-synthetic

Conversation

@xraymemory

@xraymemory xraymemory commented Jul 20, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Move shared synthetic utilities and structure-factor generation into sampleworks.synthetic.
  • Keep evaluation-only density generation under sampleworks.eval and update its shared utility import.
  • Relocate synthetic tests and document the package layout.

Testing

  • uv run --with setuptools pytest tests/synthetic tests/eval/test_generate_synthetic_density.py
  • uv run ruff check src/sampleworks/synthetic src/sampleworks/eval/generate_synthetic_density.py tests/synthetic tests/eval/test_generate_synthetic_density.py
  • uv run ruff format --check src/sampleworks/synthetic src/sampleworks/eval/generate_synthetic_density.py tests/synthetic tests/eval/test_generate_synthetic_density.py
  • uv run ty check src/sampleworks/synthetic src/sampleworks/eval/generate_synthetic_density.py tests/synthetic tests/eval/test_generate_synthetic_density.py

Closes #312

Summary by CodeRabbit

  • New Features

    • Added shared atom-selection support for both modern comparison expressions and legacy chain/residue filters.
    • Legacy selection strings now provide validation and deprecation warnings.
  • Refactor

    • Consolidated synthetic data-generation utilities into the synthetic utilities package.
    • Updated structure evaluation and synthetic workflows to use shared selection handling.
  • Documentation

    • Documented the synthetic utilities package and added it to the project module layout.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the synthetic data-generation code layout by moving shared synthetic utilities and structure-factor generation into sampleworks.synthetic, while keeping evaluation-only density generation under sampleworks.eval and updating imports/tests/docs to match.

Changes:

  • Update tests and eval code to import synthetic helpers from sampleworks.synthetic.* instead of sampleworks.eval.*.
  • Ensure structure-factor generation (generate_synthetic_sf.py) uses the relocated synthetic utilities.
  • Document the new synthetic/ package location in AGENTS.md.

Confidence: ~80% (review based on provided diffs + targeted repository searches and file excerpts).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.

Show a summary per file
File Description
tests/synthetic/test_synthetic_utils.py Updates import path for resolve_parallel_jobs to the new synthetic module.
tests/synthetic/test_generate_synthetic_sf.py Updates imports to use sampleworks.synthetic for structure-factor generation + utilities.
src/sampleworks/synthetic/synthetic_utils.py Adjusts module docstring/formatting for the shared synthetic utilities module.
src/sampleworks/synthetic/generate_synthetic_sf.py Updates imports to reference the relocated synthetic utilities module.
src/sampleworks/synthetic/init.py Adds package initializer/docstring for the new sampleworks.synthetic package.
src/sampleworks/eval/generate_synthetic_density.py Switches shared helper imports to sampleworks.synthetic.synthetic_utils.
AGENTS.md Documents the new src/sampleworks/synthetic/ package in the repository layout.
Comments suppressed due to low confidence (1)

src/sampleworks/synthetic/synthetic_utils.py:13

  • sampleworks.synthetic.synthetic_utils still imports apply_selection from sampleworks.eval.structure_utils, which keeps a synthetic → eval dependency. If the goal of this refactor is to make synthetic utilities usable outside eval (and avoid pulling eval into other modules), apply_selection should live in a non-eval module (e.g., sampleworks.utils.*) and both eval and synthetic should import it from there.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@xraymemory, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ef260a3a-b68c-4ab6-a024-fc857d44e8c9

📥 Commits

Reviewing files that changed from the base of the PR and between 68a7c1b and fe03c7a.

📒 Files selected for processing (1)
  • tests/eval/test_structure_utils.py
📝 Walkthrough

Walkthrough

Selection parsing and masking helpers were centralized in atom_array_utils. Synthetic utilities and generation code now use the sampleworks.synthetic package, with related imports, tests, and module documentation updated.

Changes

Selection and synthetic module reorganization

Layer / File(s) Summary
Shared atom-selection utilities
src/sampleworks/utils/atom_array_utils.py, src/sampleworks/eval/structure_utils.py, scripts/eval/classify_altloc_regions.py, tests/eval/test_structure_utils.py
Legacy selection parsing, masking, and application helpers now live in atom_array_utils; structure evaluation and classification code import and use them from there.
Synthetic package relocation
src/sampleworks/synthetic/*, src/sampleworks/eval/generate_synthetic_density.py, tests/synthetic/*, AGENTS.md
Synthetic utility imports and tests now reference sampleworks.synthetic, and the module layout documents the new package directory.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: abdelsalam-abbas, denis-zaitsev, marcuscollins

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning It also refactors atom-selection helpers into shared utils, which is outside the linked issue's synthetic relocation scope. Split the atom-selection helper refactor into a separate PR or add a linked issue covering that shared-utils migration.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title concisely reflects the main refactor of moving synthetic generation code out of eval.
Linked Issues check ✅ Passed The PR moves synthetic_utils and generate_synthetic_sf into sampleworks.synthetic and keeps density generation in eval, matching #312.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch xraymemory/issue-312-move-synthetic

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@@ -1,4 +1,4 @@
"""Shared utilities for synthetic structure factor and density generation."""
"""Shared utilities for synthetic structure-factor and density generation."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: we do in fact usually omit the hyphen.

@DorisMai DorisMai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xraymemory why is density generation considered part of eval instead of synthetic?

@marcuscollins

Copy link
Copy Markdown
Collaborator

@xraymemory why is density generation considered part of eval instead of synthetic?

I think Doris is right and we should put both scripts in synthetic.

# Conflicts:
#	src/sampleworks/eval/structure_utils.py
#	tests/eval/test_structure_utils.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/sampleworks/utils/atom_array_utils.py`:
- Around line 112-115: Update the deprecation notice near the existing
DeprecationWarning construction to call warnings.warn with the message,
DeprecationWarning category, and stacklevel=2. Ensure the warnings module is
available and preserve the current selection-specific migration message.
- Around line 100-105: The apply_selection filtering path around
get_mask_from_old_selection_string and atom_array.mask must raise ValueError
when the computed mask contains no matches. In the legacy parsing logic at
src/sampleworks/utils/atom_array_utils.py lines 116-119, raise ValueError when
neither a chain nor residue constraint is parsed, preventing empty or malformed
selections from matching every atom; add regression coverage for both behaviors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dd9ee7a2-197a-4609-be24-5435b5f16153

📥 Commits

Reviewing files that changed from the base of the PR and between bda0c96 and 68a7c1b.

📒 Files selected for processing (11)
  • AGENTS.md
  • scripts/eval/classify_altloc_regions.py
  • src/sampleworks/eval/generate_synthetic_density.py
  • src/sampleworks/eval/structure_utils.py
  • src/sampleworks/synthetic/__init__.py
  • src/sampleworks/synthetic/generate_synthetic_sf.py
  • src/sampleworks/synthetic/synthetic_utils.py
  • src/sampleworks/utils/atom_array_utils.py
  • tests/eval/test_structure_utils.py
  • tests/synthetic/test_generate_synthetic_sf.py
  • tests/synthetic/test_synthetic_utils.py

Comment on lines +100 to +105
if not any(x in selection for x in ATOMWORKS_COMPARISON_OPS):
mask = get_mask_from_old_selection_string(atom_array, selection)
else:
mask = atom_array.mask(selection)

return cast(AtomArray, atom_array[mask])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject empty and unparseable selections before filtering.

Atomworks-style zero-match expressions return an empty array despite apply_selection() promising ValueError; malformed legacy strings such as "" or "foo" parse to no criteria and therefore select every atom. This can silently generate results from the wrong structure.

  • src/sampleworks/utils/atom_array_utils.py#L100-L105: raise ValueError when the computed mask has no matches.
  • src/sampleworks/utils/atom_array_utils.py#L116-L119: raise ValueError when legacy parsing yields neither a chain nor a residue constraint, and add regression coverage for both cases.
Proposed fix
 def apply_selection(atom_array: AtomArray, selection: str | None) -> AtomArray:
     ...
     else:
         mask = atom_array.mask(selection)
 
+    if not mask.any():
+        raise ValueError(f"Selection '{selection}' matched no atoms")
     return cast(AtomArray, atom_array[mask])
 
 def get_mask_from_old_selection_string(...):
     ...
     chain_id, resi_start, resi_end = parse_selection_string(selection)
+    if chain_id is None and resi_start is None:
+        raise ValueError(f"Unsupported legacy selection: '{selection}'")
     mask = np.ones(len(atom_array.res_id), dtype=bool)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not any(x in selection for x in ATOMWORKS_COMPARISON_OPS):
mask = get_mask_from_old_selection_string(atom_array, selection)
else:
mask = atom_array.mask(selection)
return cast(AtomArray, atom_array[mask])
if not any(x in selection for x in ATOMWORKS_COMPARISON_OPS):
mask = get_mask_from_old_selection_string(atom_array, selection)
else:
mask = atom_array.mask(selection)
if not mask.any():
raise ValueError(f"Selection '{selection}' matched no atoms")
return cast(AtomArray, atom_array[mask])
📍 Affects 1 file
  • src/sampleworks/utils/atom_array_utils.py#L100-L105 (this comment)
  • src/sampleworks/utils/atom_array_utils.py#L116-L119
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/sampleworks/utils/atom_array_utils.py` around lines 100 - 105, The
apply_selection filtering path around get_mask_from_old_selection_string and
atom_array.mask must raise ValueError when the computed mask contains no
matches. In the legacy parsing logic at
src/sampleworks/utils/atom_array_utils.py lines 116-119, raise ValueError when
neither a chain nor residue constraint is parsed, preventing empty or malformed
selections from matching every atom; add regression coverage for both behaviors.

Source: Coding guidelines

Comment on lines +112 to +115
DeprecationWarning(
f"Using old-style selection strings like {selection} is deprecated."
f" Use atomworks/pandas style selection strings instead."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n 'warnings\.warn|DeprecationWarning' src tests

Repository: diff-use/sampleworks

Length of output: 1231


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect imports and the legacy deprecation branch around the cited lines.
sed -n '1,140p' src/sampleworks/utils/atom_array_utils.py
sed -n '230,285p' src/sampleworks/utils/atom_array_utils.py

# Read-only behavioral probe: show that constructing DeprecationWarning does not emit a warning.
python3 - <<'PY'
import warnings

warned = False
def handler(message, category, filename, lineno, file=None, line=None):
    global warned
    warned = True

warnings.showwarning = handler

for value in [DeprecationWarning("old"), "old"]:
    warned = False
    with warnings.catch_warnings():
        warnings.simplefilter("always", category=None)
        obj = value
        _ = obj  # simulate the expression in the snippet
    print(type(value).__name__, warned)
PY

Repository: diff-use/sampleworks

Length of output: 7170


Emit the deprecation warning.

The current expression only constructs DeprecationWarning(...), which does nothing. Use warnings.warn(..., DeprecationWarning, stacklevel=2) so callers and tests can observe the migration notice.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/sampleworks/utils/atom_array_utils.py` around lines 112 - 115, Update the
deprecation notice near the existing DeprecationWarning construction to call
warnings.warn with the message, DeprecationWarning category, and stacklevel=2.
Ensure the warnings module is available and preserve the current
selection-specific migration message.

@xraymemory
xraymemory merged commit 58c2311 into main Jul 22, 2026
9 of 12 checks passed
smallfishabc added a commit that referenced this pull request Aug 4, 2026
The file was a zero-edit copy of the old eval/ path version. #329 moved it to
tests/synthetic/, and its import of sampleworks.eval.generate_synthetic_sf no
longer resolves, so collecting tests/eval/ failed at import.
smallfishabc added a commit that referenced this pull request Aug 4, 2026
Reconciles the branch without a force-push. The remote's two commits
(4c441b1, 4ad6694) are patch-identical duplicates of e43f909 and 996e090:
the branch was rebased onto d31f995 on 2026-07-29 and never force-pushed, so
git reported a divergence that was only SHA-deep, never a content one.

The merge's sole incoming change was tests/eval/test_generate_synthetic_sf.py,
the stale pre-#329 duplicate that a585ee7 removed on purpose. That deletion is
kept here: the file imports sampleworks.eval.generate_synthetic_sf and
sampleworks.eval.synthetic_utils, but both modules now live under
sampleworks.synthetic.*, so restoring it would break test collection outright.
The canonical 350-line copy remains at
tests/synthetic/test_generate_synthetic_sf.py.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Move synthetic_utils.py and synethtic data generation scripts out of sampleworks.eval

4 participants