Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sampler #17

Merged
merged 33 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
16af54a
init draft for sampler
fgrunewald Jul 9, 2024
77a58ed
make deepcopy when merging
fgrunewald Jul 9, 2024
e937860
update docstrings
fgrunewald Jul 10, 2024
aebf84c
address comments and refactor slightly
fgrunewald Jul 12, 2024
6220711
add seeds
fgrunewald Jul 12, 2024
c5ba1e3
refactor random seed
fgrunewald Jul 23, 2024
6842eb4
address style comments
fgrunewald Jul 23, 2024
f4f148a
Merge branch 'master' into sampler
fgrunewald Jul 23, 2024
6a4951d
adjust open bonds function to optionally take target nodes
fgrunewald Jul 24, 2024
eb62ea9
when annontating atomnames make meta_graph optional; otherwise go off…
fgrunewald Jul 24, 2024
705691b
the fragid for cgsmiles fragments should be 0 in agreement with the c…
fgrunewald Jul 24, 2024
6fec0bc
update function call set_atom_names_atomistic according to new args
fgrunewald Jul 24, 2024
5fbb282
refactor sample
fgrunewald Jul 24, 2024
eff05ef
add more tests
fgrunewald Jul 24, 2024
e345cc7
update handling of terminal addition
fgrunewald Jul 26, 2024
f883d19
finalize tests for init function
fgrunewald Jul 26, 2024
c662435
update sampler
fgrunewald Aug 14, 2024
1228ce7
Merge branch 'master' into sampler
fgrunewald Aug 29, 2024
0eaccc6
expose sampler
fgrunewald Aug 29, 2024
654fb9b
keep proper track of fragid when adding terminals
fgrunewald Aug 29, 2024
6dfdd6f
update sampler and change meaning of bonding operators
fgrunewald Sep 10, 2024
c378034
change meaning of bonding operators and fix in test
fgrunewald Sep 10, 2024
8f50245
change naming in sampler and update doc strings
fgrunewald Sep 10, 2024
efa1a8a
update docstring
fgrunewald Sep 10, 2024
ccd2901
address comments
fgrunewald Sep 10, 2024
716ebe8
update docstring
fgrunewald Sep 10, 2024
d241a96
fix doscstrings
fgrunewald Sep 12, 2024
286a161
fix doscstrings
fgrunewald Sep 12, 2024
4c062bb
fix doscstrings and spelling
fgrunewald Sep 12, 2024
d9e6a32
typo sphinx link
fgrunewald Sep 16, 2024
7d49154
update tests
fgrunewald Sep 18, 2024
4993722
update tests and remove print
fgrunewald Sep 18, 2024
9cb3a45
Update cgsmiles/sample.py
fgrunewald Sep 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cgsmiles/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def merge_graphs(source_graph, target_graph, max_node=None):
correspondence = {}
for idx, node in enumerate(target_graph.nodes(), start=offset + 1):
correspondence[node] = idx
new_atom = copy.copy(target_graph.nodes[node])
new_atom = copy.deepcopy(target_graph.nodes[node])
new_atom['fragid'] = [(new_atom.get('fragid', 0) + fragment_offset)]
source_graph.add_node(idx, **new_atom)

Expand Down
139 changes: 139 additions & 0 deletions cgsmiles/sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import re
import random
from collections import defaultdict
import numpy as np
import networkx as nx
from .read_fragments import read_fragments
from .graph_utils import (merge_graphs,
sort_nodes_by_attr,
set_atom_names_atomistic)
from .pysmiles_utils import rebuild_h_atoms

def _find_complementary_bonding_descriptor(bonding_descriptor):
if bonding_descriptor[0] == '<':
compl = '>' + bonding_descriptor[1:]
elif bonding_descriptor[0] == '>':
compl = '<' + bonding_descriptor[1:]
else:
compl = bonding_descriptor
return compl

class MoleculeSampler:
"""
Given a fragment string in CGSmiles format
and probabilities for residues to occur,
return a random molecule with target
molecular weight.
"""
def __init__(self,
pattern,
target_weight,
bonding_probabilities,
start=None,
all_atom=True):

"""
Parameters
----------
pattern: str
the cgsmiles string to resolve
target_length: int
the target molecular weight in unit
of number of monomers
fragment_probabilities: dict[str, float]
dictionary connecting probability
to fragment names
bonding_probabilities: dict[str, float]
probabilty that two bonding descriptors
will connect
all_atom: bool
if the fragments are all-atom
resolution
"""
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
self.molecule = nx.Graph()
self.bonding_probabilities = bonding_probabilities
self.all_atom = all_atom
self.target_weight = target_weight
self.start = start
self.current_open_bonds = defaultdict(list)

fragment_strings = re.findall(r"\{[^\}]+\}", pattern)

if len(fragment_strings) > 1:
raise IOError("Sampling can only be done on one resolution.")

self.fragment_dict = {}
self.fragment_dict.update(read_fragments(fragment_strings[0],
all_atom=all_atom))

# we need to store which bonding descriptors is present in which
# fragment so we can later just look them up
self.fragments_by_bonding = defaultdict(list)
for fragname, fraggraph in self.fragment_dict.items():
bondings = nx.get_node_attributes(fraggraph, "bonding")
for node, bondings in bondings.items():
for bonding in bondings:
self.fragments_by_bonding[bonding].append((fragname, node))

def update_open_bonds(self):
self.current_open_bonds = defaultdict(list)
open_bonds = nx.get_node_attributes(self.molecule, 'bonding')
for node, bonding_types in open_bonds.items():
for bonding_types in bonding_types:
self.current_open_bonds[bonding_types].append(node)
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved

def pick_bonding(self):
"""
Given a momomer to connect to the growing molecule see if there is
a matching bonding descriptor and what the probabilitiy of forming
this bond is.
"""
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
probs = [self.bonding_probabilities[bond_type] for bond_type in self.current_open_bonds]
bonding = np.random.choice(list(self.current_open_bonds.keys()), p=probs)
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
source_node = np.random.choice(self.current_open_bonds[bonding])
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
compl_bonding = _find_complementary_bonding_descriptor(bonding)
fragname, target_node = random.choice(self.fragments_by_bonding[compl_bonding])
return (source_node, target_node, fragname, bonding, compl_bonding)

def sample(self):
"""
Sample one molecule given a fragment string and a target molecular
weigth.
"""
if self.start:
fragment = self.fragment_dict[self.start]
else:
# intialize the molecule; all fragements have the same probability
fragname = random.choice(list(self.fragment_dict.keys()))
fragment = self.fragment_dict[fragname]

merge_graphs(self.molecule, fragment)
self.update_open_bonds()

# next we add monomers one after the other
for _ in np.arange(0, self.target_weight):
# pick a bonding connector
source, target, fragname, bonding, compl_bonding = self.pick_bonding()
correspondence = merge_graphs(self.molecule, self.fragment_dict[fragname])
self.molecule.add_edge(source, correspondence[target], bonding=(bonding, compl_bonding))
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
print(source, bonding, self.molecule.nodes[source]['bonding'])
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
self.molecule.nodes[source]['bonding'].remove(bonding)
print(correspondence[target],bonding, self.molecule.nodes[correspondence[target]]['bonding'])
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
self.molecule.nodes[correspondence[target]]['bonding'].remove(compl_bonding)
self.update_open_bonds()

if self.all_atom:
rebuild_h_atoms(self.molecule)

# sort the atoms
self.molecule = sort_nodes_by_attr(self.molecule, sort_attr=("fragid"))

# in all-atom MD there are common naming conventions
# that might be expected and hence we set them here
# if self.all_atom:
# set_atom_names_atomistic(self.molecule)
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved

return self.molecule

# pick a bonding descriptor
# then pick a fragment that has this bonding descriptor
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
Loading