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 32 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
1 change: 1 addition & 0 deletions cgsmiles/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .read_cgsmiles import read_cgsmiles
from .read_fragments import read_fragments
from .resolve import MoleculeResolver
from .sample import MoleculeSampler
66 changes: 66 additions & 0 deletions cgsmiles/cgsmiles_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from collections import defaultdict
import networkx as nx

def find_complementary_bonding_descriptor(bonding_descriptor, ellegible_descriptors=None):
"""
Given a bonding descriptor find the complementary match.
In the case of '$' prefixed descriptors this is just
the same and '>' or '<' get flipped to the other
symbol.

Parameters
----------
bonding_descriptor: str
ellegible_descriptors: list[str]
a list of allowed descriptors to match

Return
------
list[str]
"""
compl = []
if bonding_descriptor[0] == '$' and ellegible_descriptors:
for descriptor in ellegible_descriptors:
if descriptor[0] == '$' and descriptor[-1] == bonding_descriptor[-1]:
compl.append(descriptor)
return compl

if bonding_descriptor[0] == '<':
compl = '>' + bonding_descriptor[1:]
elif bonding_descriptor[0] == '>':
compl = '<' + bonding_descriptor[1:]
else:
compl = bonding_descriptor

if compl not in ellegible_descriptors:
msg = ("Bonding descriptor {compl} was not found in list of potential"
"matching descriptors.")
raise IOError(msg.format(compl=compl))

return [compl]

def find_open_bonds(molecule, target_nodes=None):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
"""
Collect all nodes which have an open bonding descriptor
and store them as keys with a list of nodes as values.

Parameters
----------
molecule: nx.Graph
target_nodes: list[abc.hashable]
a list of node keys matching molecule

Return
------
dict
"""
if target_nodes is None:
target_nodes = molecule

open_bonds_by_descriptor = defaultdict(list)
open_bonds = nx.get_node_attributes(molecule, 'bonding')
for node, bonding_types in open_bonds.items():
if node in target_nodes:
for bonding_types in bonding_types:
open_bonds_by_descriptor[bonding_types].append(node)
return open_bonds_by_descriptor
31 changes: 24 additions & 7 deletions 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 Expand Up @@ -116,15 +116,32 @@ def annotate_fragments(meta_graph, molecule):
return meta_graph


def set_atom_names_atomistic(meta_graph, molecule):
def set_atom_names_atomistic(molecule, meta_graph=None):
"""
Set atomnames according to commonly used convention
in molecular dynamics (MD) forcefields. This convention
is defined as element plus counter for atom in residue.

Parameters
----------
molecule: nx.Graph
the molecule for which to adjust the atomnames
meta_graph: nx.Graph
optional; get the fragments from the meta_graph
attributes which is faster in some cases
"""
for meta_node in meta_graph.nodes:
fraggraph = meta_graph.nodes[meta_node]['graph']
for idx, node in enumerate(fraggraph.nodes):
atomname = fraggraph.nodes[node]['element'] + str(idx)
fraggraph.nodes[node]['atomname'] = atomname
fraglist = defaultdict(list)
if meta_graph:
for meta_node in meta_graph.nodes:
fraggraph = meta_graph.nodes[meta_node]['graph']
fraglist[meta_node] += list(fraggraph.nodes)
else:
node_to_fragid = nx.get_node_attributes(molecule, 'fragid')
for node, fragids in node_to_fragid.items():
assert len(fragids) == 1
fraglist[fragids[0]].append(node)

for fragnodes in fraglist.values():
for idx, node in enumerate(fragnodes):
atomname = molecule.nodes[node]['element'] + str(idx)
molecule.nodes[node]['atomname'] = atomname
24 changes: 24 additions & 0 deletions cgsmiles/pysmiles_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
import networkx as nx
import pysmiles

def compute_mass(input_molecule):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
"""
Compute the mass of a molecule from the PTE.

Parameters
----------
molecule: nx.Graph
molecule which must have element specified per node

Returns
-------
float
the atomic mass
"""
molecule = input_molecule.copy()
# we need to add the hydrogen atoms
# for computing the mass
rebuild_h_atoms(molecule)
mass = 0
for node in molecule.nodes:
element = molecule.nodes[node]['element']
mass += pysmiles.PTE[element]['AtomicMass']
return mass

def rebuild_h_atoms(mol_graph, keep_bonding=False):
"""
Helper function which add hydrogen atoms to the molecule graph.
Expand Down
2 changes: 1 addition & 1 deletion cgsmiles/read_fragments.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ def fragment_iter(fragment_str, all_atom=True):
# we deal with a CG resolution graph
else:
mol_graph = read_cgsmiles(smile)
nx.set_node_attributes(mol_graph, 1, 'fragid')
fragnames = nx.get_node_attributes(mol_graph, 'fragname')
nx.set_node_attributes(mol_graph, fragnames, 'atomname')
nx.set_node_attributes(mol_graph, bonding_descrpt, 'bonding')
Expand All @@ -161,6 +160,7 @@ def fragment_iter(fragment_str, all_atom=True):
nx.set_node_attributes(mol_graph, atomnames, 'atomname')

nx.set_node_attributes(mol_graph, fragname, 'fragname')
nx.set_node_attributes(mol_graph, 0, 'fragid')
yield fragname, mol_graph

def read_fragments(fragment_str, all_atom=True, fragment_dict=None):
Expand Down
85 changes: 65 additions & 20 deletions cgsmiles/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,39 @@
set_atom_names_atomistic)
from .pysmiles_utils import rebuild_h_atoms

def compatible(left, right):
def compatible(left, right, legacy=False):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
"""
Check bonding descriptor compatibility according
to the BigSmiles syntax conventions.
to the CGSmiles syntax conventions. With legacy
the BigSmiles convention can be used.

Parameters
----------
left: str
right: str
legacy: bool

Returns
-------
bool
"""
if left == right and left[0] not in '> <':
return True
l, r = left[0], right[0]
if (l, r) == ('<', '>') or (l, r) == ('>', '<'):
return left[1:] == right[1:]
return False

def match_bonding_descriptors(source, target, bond_attribute="bonding"):
if legacy:
if left == right and left[0] not in '> <':
return True
l, r = left[0], right[0]
if (l, r) == ('<', '>') or (l, r) == ('>', '<'):
return left[1:] == right[1:]
return False
else:
if left[0] == right[0] == '$' or left[0] == right[0] == '!':
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
return True

l, r = left[0], right[0]
if (l, r) == ('<', '>') or (l, r) == ('>', '<'):
return True
return False

def match_bonding_descriptors(source, target, bond_attribute="bonding", legacy=False):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
"""
Given a source and a target graph, which have bonding
descriptors stored as node attributes, find a pair of
Expand All @@ -46,6 +57,9 @@ def match_bonding_descriptors(source, target, bond_attribute="bonding"):
bond_attribute: `abc.hashable`
under which attribute are the bonding descriptors
stored.
legacy: bool
which syntax convention to use when matching bonding
descriptors (legacy=BigSmiles)

Returns
-------
Expand All @@ -65,7 +79,7 @@ def match_bonding_descriptors(source, target, bond_attribute="bonding"):
bond_targets = target_nodes[target_node]
for bond_source in bond_sources:
for bond_target in bond_targets:
if compatible(bond_source, bond_target):
if compatible(bond_source, bond_target, legacy=legacy):
return ((source_node, target_node), (bond_source, bond_target))
raise LookupError

Expand Down Expand Up @@ -141,7 +155,8 @@ class MoleculeResolver:
def __init__(self,
molecule_graph,
fragment_dicts,
last_all_atom=True):
last_all_atom=True,
legacy=False):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved

"""
Parameters
Expand All @@ -158,6 +173,16 @@ def __init__(self,
if the last resolution is at the all atom level. If True the code
will use pysmiles to parse the fragments and return the all-atom
molecule. Default: True
legacy: bool
which syntax convention to use for matching the bonding descriptors.
Legacy syntax adheres to the BigSmiles convention. Default syntax
adheres to CGSmiles convention where bonding descriptors '$' match
with every '$' and every '<' matches every '>'. With the BigSmiles
convention a alphanumeric string may be provided that distinguishes
these connectors. For example, '$A' would not match '$B'. However,
such use cases should be rare and the CGSmiles convention facilitates
usage of bonding descriptors in the Sampler where the labels are used
to assign different probabilities.
"""
self.meta_graph = nx.Graph()
self.fragment_dicts = fragment_dicts
Expand All @@ -167,6 +192,7 @@ def __init__(self,
self.resolutions = len(self.fragment_dicts)
new_names = nx.get_node_attributes(self.molecule, "fragname")
nx.set_node_attributes(self.meta_graph, new_names, "atomname")
self.legacy = legacy

@staticmethod
def read_fragment_strings(fragment_strings, last_all_atom=True):
Expand Down Expand Up @@ -256,7 +282,8 @@ def edges_from_bonding_descrpt(self, all_atom=False):
node_graph = self.meta_graph.nodes[node]['graph']
try:
edge, bonding = match_bonding_descriptors(prev_graph,
node_graph)
node_graph,
legacy=self.legacy)
except LookupError:
continue
# remove used bonding descriptors
Expand Down Expand Up @@ -337,7 +364,7 @@ def resolve(self):
# in all-atom MD there are common naming conventions
# that might be expected and hence we set them here
if all_atom:
set_atom_names_atomistic(self.meta_graph, self.molecule)
set_atom_names_atomistic(self.molecule, self.meta_graph)

# increment the resolution counter
self.resolution_counter += 1
Expand All @@ -361,7 +388,7 @@ def resolve_all(self):
return meta_graph, graph

@classmethod
def from_string(cls, cgsmiles_str, last_all_atom=True):
def from_string(cls, cgsmiles_str, last_all_atom=True, legacy=False):
fgrunewald marked this conversation as resolved.
Show resolved Hide resolved
"""
Initiate a MoleculeResolver instance from a cgsmiles string.

Expand All @@ -370,6 +397,11 @@ def from_string(cls, cgsmiles_str, last_all_atom=True):
cgsmiles_str: str
last_all_atom: bool
if the last resolution is all-atom and is read using pysmiles
legacy: bool
which syntax convention to use for matching the bonding descriptors.
Legacy syntax adheres to the BigSmiles convention. Default syntax
adheres to CGSmiles convention. A more detailed explanation can be
found in the :func:`~resolve.MoleculeResolver.__init__` method.

Returns
-------
Expand All @@ -384,11 +416,12 @@ def from_string(cls, cgsmiles_str, last_all_atom=True):
last_all_atom=last_all_atom)
resolver_obj = cls(molecule_graph=molecule,
fragment_dicts=fragment_dicts,
last_all_atom=last_all_atom)
last_all_atom=last_all_atom,
legacy=legacy)
return resolver_obj

@classmethod
def from_graph(cls, cgsmiles_str, meta_graph, last_all_atom=True):
def from_graph(cls, cgsmiles_str, meta_graph, last_all_atom=True, legacy=False):
"""
Initiate a MoleculeResolver instance from a cgsmiles string
and a `meta_graph` that describes the lowest resolution.
Expand All @@ -401,6 +434,11 @@ def from_graph(cls, cgsmiles_str, meta_graph, last_all_atom=True):
fragname attribute set.
last_all_atom: bool
if the last resolution is all-atom and is read using pysmiles
legacy: bool
which syntax convention to use for matching the bonding descriptors.
Legacy syntax adheres to the BigSmiles convention. Default syntax
adheres to CGSmiles convention. A more detailed explanation can be
found in the :func:`~resolve.MoleculeResolver.__init__` method.

Returns
-------
Expand All @@ -417,12 +455,13 @@ def from_graph(cls, cgsmiles_str, meta_graph, last_all_atom=True):

resolver_obj = cls(molecule_graph=meta_graph,
fragment_dicts=fragment_dicts,
last_all_atom=last_all_atom)
last_all_atom=last_all_atom,
legacy=legacy)

return resolver_obj

@classmethod
def from_fragment_dicts(cls, cgsmiles_str, fragment_dicts, last_all_atom=True):
def from_fragment_dicts(cls, cgsmiles_str, fragment_dicts, last_all_atom=True, legacy=False):
"""
Initiate a MoleculeResolver instance from a cgsmiles string, describing
one molecule and fragment_dicts containing fragments for each resolution.
Expand All @@ -436,6 +475,11 @@ def from_fragment_dicts(cls, cgsmiles_str, fragment_dicts, last_all_atom=True):
function.
last_all_atom: bool
if the last resolution is all-atom and is read using pysmiles
legacy: bool
which syntax convention to use for matching the bonding descriptors.
Legacy syntax adheres to the BigSmiles convention. Default syntax
adheres to CGSmiles convention. A more detailed explanation can be
found in the :func:`~resolve.MoleculeResolver.__init__` method.

Returns
-------
Expand All @@ -451,5 +495,6 @@ def from_fragment_dicts(cls, cgsmiles_str, fragment_dicts, last_all_atom=True):
molecule = read_cgsmiles(elements[0])
resolver_obj = cls(molecule_graph=molecule,
fragment_dicts=fragment_dicts,
last_all_atom=last_all_atom)
last_all_atom=last_all_atom,
legacy=legacy)
return resolver_obj
Loading
Loading