File size: 7,802 Bytes
dc78446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
"""Rewrite the old cluster's absolute path roots across the RNASBDD repository.

The repository hardcodes ~1,449 absolute paths under two roots that existed only
on the retired DeltaAI allocation.  Nothing runs on a new cluster until they are
remapped.  This rewrites them in place.

Dry run (default) reports what would change and touches nothing:

    python remap_paths.py --repo /path/to/RNASBDD \
        --data-root /new/scratch/RNASBDD \
        --env-prefix /new/conda/envs/rnasbdd \
        --crossdocked-root /new/scratch/sbdd_data

Add --apply to write.  Re-run the test suite afterwards: the specs carry SHA-256
digests for the files they name, and the suite checks that those still resolve.

Digests are NOT rewritten, on purpose.  A path move does not change file
content, so every dataset/split/freeze/checkpoint digest must still match after
remapping.  If one does not, the file was corrupted in transit and the launcher
is right to refuse it.
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

# Old roots, longest first so that a prefix never shadows a longer match.
OLD_ENV_PREFIX = "/work/nvme/bdrx/dzhang5/conda/envs/rnasbdd"
OLD_ANNAPURNA_ENV = "/work/nvme/bdrx/dzhang5/conda/envs/annapurna"
OLD_RNAMIGOS2_ENV = "/work/nvme/bdrx/dzhang5/conda/envs/rnamigos2"
OLD_TOOLS_ROOT = "/work/nvme/bdrx/dzhang5/tools"
OLD_CROSSDOCKED = "/work/hdd/bdrx/dzhang5/sbdd_data"
OLD_POCKET10 = "/work/hdd/bdrx/dzhang5/unimomo/molecule/crossdocked_pocket10"
OLD_DATA_ROOT = "/work/hdd/bdrx/dzhang5/RNASBDD"

# Genuinely cluster-specific and deliberately not remapped.  This is a shell
# `case` glob guarding a wheel build against non-DeltaAI prefixes; on a new
# cluster the whole guard needs rewriting by hand, not prefix substitution.
UNMAPPED_BY_DESIGN = ("scripts/build_deltaai_pyg_wheels.sh",)

SEARCH_DIRS = ("run_specs", "configs", "harness", "scripts", "docs")
SEARCH_FILES = (".research-project.toml",)
SKIP_SUFFIXES = {".pyc", ".pt", ".lmdb", ".zst", ".png", ".jpg", ".pdf"}


def build_mapping(args: argparse.Namespace) -> list[tuple[str, str]]:
    mapping = [
        (OLD_ENV_PREFIX, args.env_prefix.rstrip("/")),
        (OLD_CROSSDOCKED, args.crossdocked_root.rstrip("/")),
        (OLD_DATA_ROOT, args.data_root.rstrip("/")),
    ]
    if args.tools_root:
        mapping.append((OLD_TOOLS_ROOT, args.tools_root.rstrip("/")))
    if args.annapurna_env:
        mapping.append((OLD_ANNAPURNA_ENV, args.annapurna_env.rstrip("/")))
    if args.rnamigos2_env:
        mapping.append((OLD_RNAMIGOS2_ENV, args.rnamigos2_env.rstrip("/")))
    if args.crossdocked_pocket10:
        mapping.append((OLD_POCKET10, args.crossdocked_pocket10.rstrip("/")))
    # Longest old-prefix first: OLD_ENV_PREFIX lives under a root that no other
    # entry covers, but keeping the rule explicit makes adding entries safe.
    mapping.sort(key=lambda pair: len(pair[0]), reverse=True)
    return mapping


def candidate_files(repo: Path):
    for name in SEARCH_FILES:
        path = repo / name
        if path.is_file():
            yield path
    for directory in SEARCH_DIRS:
        root = repo / directory
        if not root.is_dir():
            continue
        for path in sorted(root.rglob("*")):
            if path.is_file() and path.suffix not in SKIP_SUFFIXES:
                if "__pycache__" not in path.parts:
                    yield path


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo", required=True, type=Path)
    parser.add_argument("--data-root", required=True,
                        help="replaces /work/hdd/bdrx/dzhang5/RNASBDD")
    parser.add_argument("--env-prefix", required=True,
                        help="replaces the conda env prefix")
    parser.add_argument("--crossdocked-root", required=True,
                        help="replaces /work/hdd/bdrx/dzhang5/sbdd_data")
    parser.add_argument("--tools-root", default=None,
                        help="replaces /work/nvme/bdrx/dzhang5/tools "
                             "(mmseqs2, annapurna, rnamigos2 binaries)")
    parser.add_argument("--annapurna-env", default=None,
                        help="replaces the AnnapuRNA conda env prefix. This is "
                             "a SEPARATE Python 2.7.15 env, not the main one.")
    parser.add_argument("--rnamigos2-env", default=None,
                        help="replaces the RNAmigos2 conda env prefix "
                             "(separate Python 3.10 env).")
    parser.add_argument("--crossdocked-pocket10", default=None,
                        help="replaces the legacy CrossDocked pocket10 raw "
                             "tree, which lives under a different old root "
                             "than --crossdocked-root.")
    parser.add_argument("--apply", action="store_true",
                        help="write the changes; without it this is a dry run")
    args = parser.parse_args()

    repo = args.repo.resolve()
    if not (repo / "run_specs").is_dir():
        raise SystemExit(f"{repo} does not look like the RNASBDD repository")

    mapping = build_mapping(args)
    print("mapping:")
    for old, new in mapping:
        print(f"  {old}\n    -> {new}")
    print()

    total_hits = 0
    changed_files = 0
    per_prefix = {old: 0 for old, _ in mapping}

    for path in candidate_files(repo):
        try:
            text = path.read_text(encoding="utf-8")
        except (UnicodeDecodeError, OSError):
            continue
        updated = text
        hits = 0
        for old, new in mapping:
            count = updated.count(old)
            if count:
                updated = updated.replace(old, new)
                per_prefix[old] += count
                hits += count
        if hits:
            total_hits += hits
            changed_files += 1
            if args.apply:
                path.write_text(updated, encoding="utf-8")
            else:
                print(f"  {hits:>4}  {path.relative_to(repo)}")

    print()
    for old, count in sorted(per_prefix.items(), key=lambda kv: -kv[1]):
        print(f"  {count:>5} x {old}")
    verb = "rewrote" if args.apply else "would rewrite"
    print(f"\n{verb} {total_hits} references across {changed_files} files")

    leftovers: dict[str, int] = {}
    if args.apply:
        for path in candidate_files(repo):
            rel = str(path.relative_to(repo))
            if rel in UNMAPPED_BY_DESIGN:
                continue
            try:
                text = path.read_text(encoding="utf-8")
            except (UnicodeDecodeError, OSError):
                continue
            count = (text.count("/work/hdd/bdrx/dzhang5")
                     + text.count("/work/nvme/bdrx/dzhang5"))
            if count:
                leftovers[rel] = count
        total_left = sum(leftovers.values())
        print(f"remaining old-root references: {total_left}")
        for rel, count in sorted(leftovers.items(), key=lambda kv: -kv[1]):
            print(f"    {count:>3}  {rel}")
        for rel in UNMAPPED_BY_DESIGN:
            if (repo / rel).is_file():
                print(f"  skipped by design (needs hand edit): {rel}")
        if total_left:
            print("\nNOTE: the mapping did not cover everything.  Pass the "
                  "optional flags (--annapurna-env, --rnamigos2-env, "
                  "--crossdocked-pocket10, --tools-root) for the ones above.")
            return 1
        print("\nNext: re-run the test suite.  Digests are unchanged by design, "
              "so a digest failure now means a corrupted transfer, not a stale "
              "pin.")
    else:
        print("dry run - nothing written.  Re-run with --apply to write.")
    return 0


if __name__ == "__main__":
    sys.exit(main())