forked from enviPath/enviPy
[Feature] SPathway to_json outputs Bayes Probabilities (#430)
Co-authored-by: Tim Lorsbach <tim@lorsba.ch> Reviewed-on: enviPath/enviPy#430
This commit is contained in:
@ -1805,12 +1805,51 @@ class SPathway(object):
|
||||
|
||||
logger.info("Update done!")
|
||||
|
||||
def compute_bayes_probabilities(self) -> Dict[SEdge, float]:
|
||||
"""
|
||||
Computes Bayes-adjusted probabilities for all edges in the pathway
|
||||
by iterating level by level from depth 0 upwards, keyed on educt depth.
|
||||
|
||||
Returns:
|
||||
A dict mapping each SEdge to its Bayes-adjusted probability.
|
||||
"""
|
||||
bayes_probs: Dict[SEdge, float] = {}
|
||||
|
||||
# Group edges by their educt depth
|
||||
edges_by_depth: Dict[int, List[SEdge]] = {}
|
||||
for edge in self.edges:
|
||||
d = edge.educts[0].depth
|
||||
edges_by_depth.setdefault(d, []).append(edge)
|
||||
|
||||
for depth in sorted(edges_by_depth.keys()):
|
||||
for edge in edges_by_depth[depth]:
|
||||
if depth == 0:
|
||||
bayes_probs[edge] = edge.probability
|
||||
else:
|
||||
predecessor_edges = [e for e in self.edges if edge.educts[0] in e.products]
|
||||
|
||||
if not predecessor_edges or not all(
|
||||
e in bayes_probs for e in predecessor_edges
|
||||
):
|
||||
# Predecessor not computed yet (e.g. same-depth product),
|
||||
# fall back to raw probability
|
||||
bayes_probs[edge] = edge.probability
|
||||
else:
|
||||
predecessor_avg = sum(bayes_probs[e] for e in predecessor_edges) / len(
|
||||
predecessor_edges
|
||||
)
|
||||
bayes_probs[edge] = predecessor_avg * edge.probability
|
||||
|
||||
return bayes_probs
|
||||
|
||||
def to_json(self):
|
||||
nodes = []
|
||||
edges = []
|
||||
|
||||
idx_lookup = {}
|
||||
|
||||
bayes_probs = self.compute_bayes_probabilities()
|
||||
|
||||
for i, smiles in enumerate(self.smiles_to_node):
|
||||
n = self.smiles_to_node[smiles]
|
||||
idx_lookup[smiles] = i
|
||||
@ -1831,6 +1870,7 @@ class SPathway(object):
|
||||
|
||||
if edge.probability:
|
||||
e["probability"] = edge.probability
|
||||
e["multiGenProbability"] = bayes_probs[edge]
|
||||
|
||||
edges.append(e)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user