@@ -65,6 +65,12 @@ def __init__(self, structure, confidence: Confidence, contact_thresh: float, pae
6565 self .pae_filter = pae_filter
6666 self ._res_index_map , self ._chain_indices_by_id , self ._chains = self ._build_maps ()
6767
68+ self ._sasa_cache : Dict [str , float ] = {}
69+ self ._sasa_complex_cache : Dict [Tuple [str , str ], float ] = {}
70+ self ._buried_surface_cache : Dict [Tuple [str , str , float , int ], list [tuple [np .ndarray , np .ndarray ]]] = {}
71+ self ._contact_ns_cache : Dict [Tuple [str , str ], Tuple [list , list , np .ndarray , np .ndarray ]] = {}
72+ self ._all_atom_ns_cache : Dict [Tuple [str , str ], Tuple [list , NeighborSearch ]] = {}
73+
6874 self .interfaces : List [Interface ] = []
6975 for i in range (len (self ._chains )):
7076 for j in range (i + 1 , len (self ._chains )):
@@ -245,41 +251,54 @@ def score_complex(self) -> float:
245251 @cached_property
246252 def _ns_all_atoms (self ) -> NeighborSearch :
247253 """NeighborSearch over all atoms in both chains (reused by hb/sb)."""
248- atoms = [a for r in (self .chain1 + self .chain2 ) for a in r ]
249- return NeighborSearch (atoms )
254+ key = tuple (sorted ((self ._cid1_id , self ._cid2_id )))
255+ cached = self .c ._all_atom_ns_cache .get (key )
256+ if cached is None :
257+ atoms = [a for r in (self .chain1 + self .chain2 ) for a in r ]
258+ cached = (atoms , NeighborSearch (atoms ))
259+ self .c ._all_atom_ns_cache [key ] = cached
260+ return cached [1 ]
250261
251262 @cached_property
252263 def hb (self ) -> int :
253264 atoms1 = [a for r in self .chain1 for a in r if a .id .upper ().startswith (("N" ,"O" ))]
254265 atoms2 = [a for r in self .chain2 for a in r if a .id .upper ().startswith (("N" ,"O" ))]
255266 if not atoms1 or not atoms2 : return 0
267+ ids1 = {id (a ) for a in atoms1 }
268+ ids2 = {id (a ) for a in atoms2 }
256269 ns = self ._ns_all_atoms ; cutoff = 3.5
257270 seen , cnt = set (), 0
258- for a1 in atoms1 :
259- for a2 in ns . search (a1 . coord , cutoff ):
260- if a2 in atoms2 and a2 is not a1 :
261- key = tuple (sorted ([ id ( a1 ), id ( a2 )] ))
262- if key not in seen :
263- seen .add (key ); cnt += 1
271+ for a1 , a2 in ns . search_all ( cutoff ) :
272+ i1 , i2 = id (a1 ), id ( a2 )
273+ if ( i1 in ids1 and i2 in ids2 ) or ( i1 in ids2 and i2 in ids1 ) :
274+ key = tuple (sorted (( i1 , i2 ) ))
275+ if key not in seen :
276+ seen .add (key ); cnt += 1
264277 return cnt
265278
266279 @cached_property
267280 def sb (self ) -> int :
268281 pos , neg = {"ARG" ,"LYS" }, {"ASP" ,"GLU" }
269- a1 = [a for r in self .chain1 if r .get_resname () in pos | neg for a in r if a .id not in ("N" ,"CA" ,"C" ,"O" )]
270- a2 = [a for r in self .chain2 if r .get_resname () in pos | neg for a in r if a .id not in ("N" ,"CA" ,"C" ,"O" )]
282+ relevant = pos | neg
283+ a1 = [a for r in self .chain1 if r .get_resname () in relevant for a in r if a .id not in ("N" ,"CA" ,"C" ,"O" )]
284+ a2 = [a for r in self .chain2 if r .get_resname () in relevant for a in r if a .id not in ("N" ,"CA" ,"C" ,"O" )]
271285 if not a1 or not a2 : return 0
272286 ns = self ._ns_all_atoms ; cutoff = 4.0
287+ ids1 = {id (a ): 1 if a .get_parent ().get_resname () in pos else - 1 for a in a1 }
288+ ids2 = {id (a ): 1 if a .get_parent ().get_resname () in pos else - 1 for a in a2 }
273289 seen , cnt = set (), 0
274- for x in a1 :
275- n1 = x .get_parent ().get_resname ()
276- for y in ns .search (x .coord , cutoff ):
277- if y in a2 and y is not x :
278- n2 = y .get_parent ().get_resname ()
279- if (n1 in pos and n2 in neg ) or (n1 in neg and n2 in pos ):
280- key = tuple (sorted ([id (x ), id (y )]))
281- if key not in seen :
282- seen .add (key ); cnt += 1
290+ for x , y in ns .search_all (cutoff ):
291+ ix , iy = id (x ), id (y )
292+ if ix in ids1 and iy in ids2 :
293+ if ids1 [ix ] + ids2 [iy ] == 0 :
294+ key = tuple (sorted ((ix , iy )))
295+ if key not in seen :
296+ seen .add (key ); cnt += 1
297+ elif ix in ids2 and iy in ids1 :
298+ if ids2 [ix ] + ids1 [iy ] == 0 :
299+ key = tuple (sorted ((ix , iy )))
300+ if key not in seen :
301+ seen .add (key ); cnt += 1
283302 return cnt
284303
285304 @cached_property
@@ -303,15 +322,30 @@ def int_solv_en(self) -> float:
303322 # ---------- private helpers below ----------
304323 def _get_pairs (self ):
305324 res_pairs : Set [Tuple [Any , Any ]] = set ()
306- a1 = [r ["CB" ] if "CB" in r else r ["CA" ] for r in self .chain1 ]
307- a2 = [r ["CB" ] if "CB" in r else r ["CA" ] for r in self .chain2 ]
308- ns = NeighborSearch (a1 + a2 )
309- for x in a1 :
310- for y in ns .search (x .coord , self .c .contact_thresh ):
311- if y in a2 : res_pairs .add ((x .get_parent (), y .get_parent ()))
325+ a1 , a2 , coords1 , coords2 = self ._contact_atom_data ()
326+ if not len (a1 ) or not len (a2 ):
327+ return set (), set (), res_pairs
328+ diff = coords1 [:, None , :] - coords2 [None , :, :]
329+ dist2 = np .sum (diff * diff , axis = 2 )
330+ mask = dist2 <= self .c .contact_thresh ** 2
331+ idx_i , idx_j = np .where (mask )
332+ for i , j in zip (idx_i .tolist (), idx_j .tolist ()):
333+ res_pairs .add ((a1 [i ].get_parent (), a2 [j ].get_parent ()))
312334 r1 = {p [0 ] for p in res_pairs }; r2 = {p [1 ] for p in res_pairs }
313335 return r1 , r2 , res_pairs
314336
337+ def _contact_atom_data (self ) -> Tuple [list , list , np .ndarray , np .ndarray ]:
338+ key = (self ._cid1_id , self ._cid2_id )
339+ cached = self .c ._contact_ns_cache .get (key )
340+ if cached is None :
341+ a1 = [r ["CB" ] if "CB" in r else r ["CA" ] for r in self .chain1 ]
342+ a2 = [r ["CB" ] if "CB" in r else r ["CA" ] for r in self .chain2 ]
343+ coords1 = np .array ([a .coord for a in a1 ], dtype = float ) if a1 else np .empty ((0 , 3 ))
344+ coords2 = np .array ([a .coord for a in a2 ], dtype = float ) if a2 else np .empty ((0 , 3 ))
345+ cached = (a1 , a2 , coords1 , coords2 )
346+ self .c ._contact_ns_cache [key ] = cached
347+ return cached
348+
315349 def _avg_plddt_union (self ) -> float :
316350 res_set = self ._res1 | self ._res2
317351 if not res_set :
@@ -397,6 +431,17 @@ def _frac(self, names: set[str]) -> float:
397431 return (sum (1 for r in residues if r .get_resname () in names ) / len (residues )) if residues else 0.0
398432
399433 def _sasa_chain (self , residues ) -> float :
434+ chain_id = residues [0 ].get_parent ().id if residues else None
435+ if chain_id :
436+ cached = self .c ._sasa_cache .get (chain_id )
437+ if cached is not None :
438+ return cached
439+ total = self ._compute_sasa_chain (residues )
440+ if chain_id :
441+ self .c ._sasa_cache [chain_id ] = total
442+ return total
443+
444+ def _compute_sasa_chain (self , residues ) -> float :
400445 """
401446 Return solvent-accessible surface area for a set of residues.
402447
@@ -427,6 +472,15 @@ def _sasa_chain(self, residues) -> float:
427472 return total
428473
429474 def _sasa_complex (self , r1 , r2 ) -> float :
475+ key = tuple (sorted ((self ._cid1_id , self ._cid2_id )))
476+ cached = self .c ._sasa_complex_cache .get (key )
477+ if cached is not None :
478+ return cached
479+ total = self ._compute_sasa_complex (r1 , r2 )
480+ self .c ._sasa_complex_cache [key ] = total
481+ return total
482+
483+ def _compute_sasa_complex (self , r1 , r2 ) -> float :
430484 """
431485 Return solvent-accessible surface area for a two-chain complex.
432486
@@ -456,6 +510,19 @@ def _sasa_complex(self, r1, r2) -> float:
456510 return total
457511
458512 def _buried_surface (self , chain_res , other_res , dist = 5.0 , dots = 15 ):
513+ chain_id = chain_res [0 ].get_parent ().id if chain_res else None
514+ other_id = other_res [0 ].get_parent ().id if other_res else None
515+ cache_key = (chain_id , other_id , float (dist ), int (dots ))
516+ if chain_id and other_id :
517+ cached = self .c ._buried_surface_cache .get (cache_key )
518+ if cached is not None :
519+ return cached
520+ result = self ._compute_buried_surface (chain_res , other_res , dist , dots )
521+ if chain_id and other_id :
522+ self .c ._buried_surface_cache [cache_key ] = result
523+ return result
524+
525+ def _compute_buried_surface (self , chain_res , other_res , dist = 5.0 , dots = 15 ):
459526 """
460527 Approximate the set of buried surface points on `chain_res` that lie
461528 within `dist` Å of any atom in `other_res`.
@@ -516,31 +583,36 @@ def _buried_surface(self, chain_res, other_res, dist=5.0, dots=15):
516583 probe_radius = float (sr .probe_radius )
517584
518585 buried = []
519- for atom , center in zip (atoms , atom_coords ):
520- # Approximate surface points on this atom
521- radius = radii_dict [atom .element ] + probe_radius
522- points = sphere * radius + center # (dots, 3)
523- normals = sphere # unit normals for each point
524-
525- # Compute squared distances from each point to all atoms in other_res
586+ atom_radii = np .array ([radii_dict [atom .element ] + probe_radius for atom in atoms ])
587+ for radius , center in zip (atom_radii , atom_coords ):
588+ points = sphere * radius + center
526589 diff = points [:, None , :] - other_coords [None , :, :]
527- dist2 = np .sum (diff * diff , axis = 2 ) # (dots, n_other)
590+ dist2 = np .sum (diff * diff , axis = 2 )
528591 mask = np .any (dist2 <= d2 , axis = 1 )
529-
530- for xyz , n in zip (points [mask ], normals [mask ]):
531- buried .append ((xyz .astype (float ), n .astype (float )))
592+ if np . any ( mask ):
593+ for xyz , n in zip (points [mask ], sphere [mask ]):
594+ buried .append ((xyz .astype (float ), n .astype (float )))
532595
533596 return buried
534597
535598 def _approx_sc (self , A , B , w = 0.5 ) -> float :
536- cB = np .array ([p [0 ] for p in B ]); nB = [p [1 ] for p in B ]
599+ cB = np .array ([p [0 ] for p in B ], dtype = float )
600+ nB = np .array ([p [1 ] for p in B ], dtype = float )
601+ cA = np .array ([p [0 ] for p in A ], dtype = float )
602+ nA = np .array ([p [1 ] for p in A ], dtype = float )
603+
537604 sA = []
538- for x , nA in A :
539- d = cB - x ; j = np .argmin (np .sum (d * d , axis = 1 ))
540- sA .append (float (np .dot (nA , - nB [j ]) * math .exp (- w * float (np .sum (d [j ]* d [j ])))))
541- cA = np .array ([p [0 ] for p in A ]); nA = [p [1 ] for p in A ]
605+ for x , nA_vec in A :
606+ d = cB - x
607+ d_sq = np .sum (d * d , axis = 1 )
608+ j = int (np .argmin (d_sq ))
609+ d_j_sq = float (d_sq [j ])
610+ sA .append (float (np .dot (nA_vec , - nB [j ]) * math .exp (- w * d_j_sq )))
542611 sB = []
543- for x , n in B :
544- d = cA - x ; j = np .argmin (np .sum (d * d , axis = 1 ))
545- sB .append (float (np .dot (n , - nA [j ]) * math .exp (- w * float (np .sum (d [j ]* d [j ])))))
612+ for x , n_vec in B :
613+ d = cA - x
614+ d_sq = np .sum (d * d , axis = 1 )
615+ j = int (np .argmin (d_sq ))
616+ d_j_sq = float (d_sq [j ])
617+ sB .append (float (np .dot (n_vec , - nA [j ]) * math .exp (- w * d_j_sq )))
546618 return float (0.5 * (np .median (sA ) + np .median (sB )))
0 commit comments