Coverage for SynRBL/confidence_prediction.py: 29%
34 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
1import joblib
2import pandas as pd
3import numpy as np
4import importlib.resources
5import SynRBL.SynAnalysis
7from SynRBL.SynAnalysis.analysis_utils import (
8 calculate_chemical_properties,
9 count_boundary_atoms_products_and_calculate_changes,
10)
11from SynRBL.SynUtils.common import update_reactants_and_products
14class ConfidencePredictor:
15 def __init__(
16 self,
17 reaction_col="reaction",
18 input_reaction_col="input_reaction",
19 confidence_col="confidence",
20 solved_by_col="solved_by",
21 solved_by_method="mcs-based",
22 mcs_col="mcs",
23 ):
24 self.model = joblib.load(
25 importlib.resources.files(SynRBL.SynAnalysis)
26 .joinpath("scoring_function.dump")
27 .open("rb")
28 )
29 self.reaction_col = reaction_col
30 self.input_reaction_col = input_reaction_col
31 self.confidence_col = confidence_col
32 self.solved_by_col = solved_by_col
33 self.solved_by_method = solved_by_method
34 self.mcs_col = mcs_col
36 def predict(self, reactions, stats=None, threshold=0):
37 reactions = [
38 r
39 for r in reactions
40 if self.solved_by_col in r.keys()
41 and r[self.solved_by_col] == self.solved_by_method
42 ]
43 conf_success = 0
44 if len(reactions) > 0:
45 _reactions = count_boundary_atoms_products_and_calculate_changes(
46 reactions, self.reaction_col, self.mcs_col
47 )
48 update_reactants_and_products(_reactions, self.input_reaction_col)
49 _reactions = calculate_chemical_properties(_reactions)
51 df = pd.DataFrame(_reactions)
53 X_pred = df[
54 [
55 "carbon_difference",
56 "fragment_count",
57 "total_carbons",
58 "total_bonds",
59 "total_rings",
60 "num_boundary",
61 "ring_change_merge",
62 "bond_change_merge",
63 ]
64 ]
66 confidence = np.round(self.model.predict_proba(X_pred)[:, 1], 3)
67 assert len(reactions) == len(confidence)
68 for r, c in zip(reactions, confidence):
69 r[self.confidence_col] = c
70 if c >= threshold:
71 conf_success += 1
72 if stats is not None:
73 stats["confident_cnt"] = conf_success
74 return reactions