File size: 9,605 Bytes
9f39a5d | 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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | #!/usr/bin/env python
"""
Generate dimer topologies conditioned on SSE patterns from the Pinder dataset.
Filters for large complexes (total SSE >= min_total_sse, proxy for >400 AA).
Outputs both chain A and chain B (dimer mode) for build_sketch.py --dimer True.
Usage:
python generate_pinder.py --output_dir ./output_dimer
"""
import os, sys, torch, numpy as np, random, argparse
from torch_geometric.data import Data, Batch
import lightning
def load_pinder_patterns(pt_path, min_total_sse=40, min_sse_per_chain=10,
min_frac_h=0.0, max_frac_h=1.0):
"""
Load Pinder dataset and extract (ss_A, ss_B) pattern pairs for large complexes.
x: [N, 11] — col 0: ss1, col 1: ss2, col 2: chain_id (0=A, 1=B)
"""
data = torch.load(pt_path)
patterns = []
for d in data:
x = d.x.numpy()
chain_A = x[:, 2] < 0.5
chain_B = x[:, 2] >= 0.5
n_A = chain_A.sum() // 3
n_B = chain_B.sum() // 3
total = n_A + n_B
if total < min_total_sse:
continue
if n_A < min_sse_per_chain or n_B < min_sse_per_chain:
continue
def sse_str(mask):
xc = x[mask]
n = mask.sum() // 3
s = ''
for i in range(n):
t = xc[3*i+1, 0:2]
s += 'H' if t[0] > t[1] else 'E'
return s
ss_A = sse_str(chain_A)
ss_B = sse_str(chain_B)
fh_A = ss_A.count('H') / len(ss_A)
fh_B = ss_B.count('H') / len(ss_B)
if not (min_frac_h <= fh_A <= max_frac_h): continue
if not (min_frac_h <= fh_B <= max_frac_h): continue
patterns.append((ss_A, ss_B))
print(f"Loaded {len(patterns)} Pinder dimer patterns "
f"(total_sse>={min_total_sse}, each chain>={min_sse_per_chain})")
return patterns
def create_dimer_input(ss_A, ss_B):
"""Build PyG Data with h=[ss1,ss2,chain_id] for both chains."""
def make_h(ss_seq, chain_id):
h = []
for s in ss_seq:
feat = [1., 0., float(chain_id)] if s == 'H' else [0., 1., float(chain_id)]
h.extend([feat] * 3)
return h
h_all = make_h(ss_A, 0) + make_h(ss_B, 1)
h = torch.tensor(h_all, dtype=torch.float)
n = len(h_all)
return Data(x=h, pos=torch.randn(n, 3), num_nodes=n)
def estimate_aa_count(crd, sse):
"""Estimate AA count for one chain from CG coordinates."""
n_sse = len(crd) // 3
total = 6
for i in range(n_sse):
ss_crd = crd[3*i:3*i+3]
ss_type = sse[3*i+1]
dis = np.linalg.norm(ss_crd[2] - ss_crd[0])
aa = int(dis/1.59)+4 if ss_type[0] > ss_type[1] else int(dis/3.2)+3
total += max(aa, 3)
if i < n_sse - 1:
total += max(int(np.linalg.norm(crd[3*i+2]-crd[3*(i+1)])/3.5), 2)
return total
def compute_rg(crd):
c = crd.mean(axis=0)
return np.sqrt(np.mean(np.sum((crd - c)**2, axis=1)))
def expected_rg(n_aa):
return 0.395 * (n_aa**0.6) + 8.0
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', type=str, default='./ckpt/dimer.ckpt')
parser.add_argument('--data', type=str,
default='./filtcathgraphlist_simple.pt')
parser.add_argument('--pinder_val', type=str,
default='./pinder_cluster_val.pt')
parser.add_argument('--pinder_test', type=str,
default='./pinder_cluster_test.pt')
parser.add_argument('--output_dir', type=str, default='./output_dimer')
parser.add_argument('--device', type=str, default='cuda')
parser.add_argument('--batch_size', type=int, default=16)
parser.add_argument('--num_trials', type=int, default=1000)
parser.add_argument('--target_count', type=int, default=200)
parser.add_argument('--min_total_sse', type=int, default=40,
help='Min total SSEs across both chains (proxy for >400 AA)')
parser.add_argument('--min_sse_per_chain', type=int, default=10,
help='Min SSEs per chain')
parser.add_argument('--min_aa_total', type=int, default=400,
help='Min total estimated AA (chain A + chain B)')
parser.add_argument('--max_aa_total', type=int, default=900,
help='Max total estimated AA')
parser.add_argument('--max_loop', type=float, default=20.0,
help='Max intra-chain loop CG distance (A)')
parser.add_argument('--max_rg_factor', type=float, default=1.2)
parser.add_argument('--fixed_pattern_A', type=str, default='',
help='Fix chain A to this SSE string (e.g. HHHHHHHHHHHHHHHHHHHHHHHH). '
'Bypasses Pinder pattern loading for chain A.')
parser.add_argument('--fixed_pattern_B', type=str, default='',
help='Fix chain B to this SSE string. Bypasses Pinder for chain B.')
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
device = torch.device(args.device)
# Load pinder patterns or use fixed patterns
if args.fixed_pattern_A and args.fixed_pattern_B:
patterns = [(args.fixed_pattern_A, args.fixed_pattern_B)]
print(f"Using fixed patterns: A={args.fixed_pattern_A} ({len(args.fixed_pattern_A)} SSEs), "
f"B={args.fixed_pattern_B} ({len(args.fixed_pattern_B)} SSEs)")
else:
patterns = []
for pt in [args.pinder_val, args.pinder_test]:
if os.path.exists(pt):
patterns += load_pinder_patterns(pt,
min_total_sse=args.min_total_sse,
min_sse_per_chain=args.min_sse_per_chain)
if not patterns:
print("ERROR: No patterns loaded."); sys.exit(1)
print(f"\nLoading checkpoint: {args.checkpoint}")
model = lightning.DDPM.load_from_checkpoint(
args.checkpoint, map_location=args.device,
data_path=args.data, torch_device=args.device, train_pinder=False)
model.eval()
model.ddpm.in_node_nf = 11
all_nodes, all_batches = [], []
structure_count = 0
print(f"\nFilter criteria:")
print(f" Total AA : {args.min_aa_total} - {args.max_aa_total}")
print(f" Max loop dist: {args.max_loop} A")
print(f" Max Rg factor: {args.max_rg_factor}")
print(f" Target count : {args.target_count}\n")
for trial in range(args.num_trials):
if structure_count >= args.target_count:
break
ss_A, ss_B = random.choice(patterns)
fake_list = [create_dimer_input(ss_A, ss_B) for _ in range(args.batch_size)]
batch_data = Batch.from_data_list(fake_list).to(device)
with torch.no_grad():
_, chain0 = model.ddpm.sample_chain_gvp(
batch_data.pos, batch_data.x[:, 0:3],
batch_data.batch, keep_frames=2)
for b in range(args.batch_size):
node_mask = (batch_data.batch.cpu() == b)
sample = chain0[node_mask.to(device)].cpu()
mask_A = sample[:, 5] < 0.5
mask_B = sample[:, 5] >= 0.5
n_A = mask_A.sum().item() // 3
n_B = mask_B.sum().item() // 3
if n_A < args.min_sse_per_chain or n_B < args.min_sse_per_chain:
continue
crd_A = sample[mask_A][:, 0:3].numpy()
sse_A = sample[mask_A][:, 3:5].numpy()
crd_B = sample[mask_B][:, 0:3].numpy()
sse_B = sample[mask_B][:, 3:5].numpy()
# Filter: intra-chain loop distances
def max_loop(crd, n_sse):
loops = [np.linalg.norm(crd[3*i+2]-crd[3*(i+1)]) for i in range(n_sse-1)]
return max(loops) if loops else 0.0
if max_loop(crd_A, n_A) > args.max_loop: continue
if max_loop(crd_B, n_B) > args.max_loop: continue
# Filter: total AA estimate
aa_A = estimate_aa_count(crd_A, sse_A)
aa_B = estimate_aa_count(crd_B, sse_B)
aa_total = aa_A + aa_B
if not (args.min_aa_total <= aa_total <= args.max_aa_total): continue
# Filter: Rg compactness per chain
if compute_rg(crd_A) > args.max_rg_factor * expected_rg(aa_A): continue
if compute_rg(crd_B) > args.max_rg_factor * expected_rg(aa_B): continue
all_nodes.append(sample)
all_batches.append(torch.full((node_mask.sum(),), structure_count, dtype=torch.float))
structure_count += 1
print(f" Accepted [{structure_count:3d}/{args.target_count}]: "
f"SSE_A={n_A} SSE_B={n_B} AA={aa_total} "
f"loop_A={max_loop(crd_A,n_A):.1f} loop_B={max_loop(crd_B,n_B):.1f} "
f"ss_A={ss_A} ss_B={ss_B}")
print(f"Trial {trial+1:3d}/{args.num_trials}: accepted={structure_count}")
if structure_count == 0:
print("No structures passed filters. Try relaxing --max_loop or --max_rg_factor.")
return
nodes_total = torch.cat(all_nodes, dim=0)
batch_total = torch.cat(all_batches, dim=0)
save_topo = torch.cat([nodes_total, batch_total.unsqueeze(1)], dim=1).numpy()
out_npy = os.path.join(args.output_dir, 'dimer_topologies.npy')
np.save(out_npy, save_topo)
print(f"\nSaved {structure_count} dimer topologies to: {out_npy}")
print(f"\nNext step:")
print(f" python build_sketch.py \\")
print(f" --input {out_npy} --output {args.output_dir}/sketches \\")
print(f" --dimer True --filt_rg False --filt_longloop False --downstream True")
if __name__ == '__main__':
main()
|