Skip to content

Commit fa1ddbb

Browse files
committed
refactoring build_conformational_states
1 parent ad297bc commit fa1ddbb

7 files changed

Lines changed: 638 additions & 493 deletions

File tree

‎CodeEntropy/config/arg_config_manager.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,21 @@
1414
"nargs": "+",
1515
"help": "Path to Structure/topology file followed by Trajectory file(s)",
1616
},
17+
"force_file": {
18+
"type": str,
19+
"default": None,
20+
"help": "Optional path to force file if forces are not in trajectory file",
21+
},
22+
"file_format": {
23+
"type": str,
24+
"default": None,
25+
"help": "String for file format as recognised by MDAnalysis",
26+
},
27+
"kcal_force_units": {
28+
"type": bool,
29+
"default": False,
30+
"help": "Set this to True if you have a separate force file with kcal units.",
31+
},
1732
"selection_string": {
1833
"type": str,
1934
"help": "Selection string for CodeEntropy",

‎CodeEntropy/dihedral_tools.py‎

Lines changed: 372 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,372 @@
1+
import logging
2+
3+
import numpy as np
4+
from MDAnalysis.analysis.dihedrals import Dihedral
5+
from rich.progress import (
6+
BarColumn,
7+
Progress,
8+
SpinnerColumn,
9+
TextColumn,
10+
TimeElapsedColumn,
11+
)
12+
13+
from CodeEntropy.mda_universe_operations import UniverseOperations
14+
15+
logger = logging.getLogger(__name__)
16+
17+
18+
class DihedralAnalysis:
19+
"""
20+
Functions for finding dihedral angles and analysing them to get the
21+
states needed for the conformational entropy functions.
22+
"""
23+
24+
def __init__(self):
25+
"""
26+
Initialise with placeholders.
27+
"""
28+
self.data_container = None
29+
self.states_ua = None
30+
self.states_res = None
31+
32+
def build_conformational_states(
33+
self,
34+
data_container,
35+
levels,
36+
groups,
37+
start,
38+
end,
39+
step,
40+
bin_width,
41+
):
42+
"""
43+
Build the conformational states descriptors based on dihedral angles
44+
needed for the calculation of the conformational entropy.
45+
"""
46+
number_groups = len(groups)
47+
states_ua = {}
48+
states_res = [None] * number_groups
49+
50+
total_items = sum(
51+
len(levels[mol_id]) for mols in groups.values() for mol_id in mols
52+
)
53+
54+
with Progress(
55+
SpinnerColumn(),
56+
TextColumn("[bold blue]{task.fields[title]}", justify="right"),
57+
BarColumn(),
58+
TextColumn("[progress.percentage]{task.percentage:>3.1f}%"),
59+
TimeElapsedColumn(),
60+
) as progress:
61+
62+
task = progress.add_task(
63+
"[green]Building Conformational States...",
64+
total=total_items,
65+
title="Starting...",
66+
)
67+
68+
for group_id in groups.keys():
69+
molecules = groups[group_id]
70+
mol = UniverseOperations.get_molecule_container(data_container, 0)
71+
num_residues = len(mol.residues)
72+
dihedrals_ua = [[] for _ in range(num_residues)]
73+
peaks_ua = [{} for _ in range(num_residues)]
74+
dihedrals_res = []
75+
peaks_res = {}
76+
77+
# Identify dihedral AtomGroups
78+
for level in levels[molecules[0]]:
79+
if level == "united_atom":
80+
for res_id in range(num_residues):
81+
selection1 = mol.residues[res_id].atoms.indices[0]
82+
selection2 = mol.residues[res_id].atoms.indices[-1]
83+
res_container = UniverseOperations.new_U_select_atom(
84+
mol,
85+
f"index {selection1}:" f"{selection2}",
86+
)
87+
heavy_res = UniverseOperations.new_U_select_atom(
88+
res_container, "prop mass > 1.1"
89+
)
90+
91+
dihedrals_ua[res_id] = self._get_dihedrals(heavy_res, level)
92+
93+
elif level == "residue":
94+
dihedrals_res = self._get_dihedrals(mol, level)
95+
96+
# Identify peaks
97+
for level in levels[molecules[0]]:
98+
if level == "united_atom":
99+
for res_id in range(num_residues):
100+
peaks_ua[res_id] = self._identify_peaks(
101+
data_container,
102+
molecules,
103+
dihedrals_ua[res_id],
104+
bin_width,
105+
start,
106+
end,
107+
step,
108+
)
109+
110+
elif level == "residue":
111+
peaks_res = self._identify_peaks(
112+
data_container,
113+
molecules,
114+
dihedrals_res,
115+
bin_width,
116+
start,
117+
end,
118+
step,
119+
)
120+
121+
# Assign states for each group
122+
for level in levels[molecules[0]]:
123+
if level == "united_atom":
124+
for res_id in range(num_residues):
125+
key = (group_id, res_id)
126+
states_ua[key] = self._assign_states(
127+
data_container,
128+
molecules,
129+
dihedrals_ua[res_id],
130+
peaks_ua[res_id],
131+
start,
132+
end,
133+
step,
134+
)
135+
136+
elif level == "residue":
137+
states_res[group_id] = self._assign_states(
138+
data_container,
139+
molecules,
140+
dihedrals_res,
141+
peaks_res,
142+
start,
143+
end,
144+
step,
145+
)
146+
147+
progress.advance(task)
148+
149+
return states_ua, states_res
150+
151+
def _get_dihedrals(self, data_container, level):
152+
"""
153+
Define the set of dihedrals for use in the conformational entropy function.
154+
If united atom level, the dihedrals are defined from the heavy atoms
155+
(4 bonded atoms for 1 dihedral).
156+
If residue level, use the bonds between residues to cast dihedrals.
157+
Note: not using improper dihedrals only ones with 4 atoms/residues
158+
in a linear arrangement.
159+
160+
Args:
161+
data_container (MDAnalysis.Universe): system information
162+
level (str): level of the hierarchy (should be residue or polymer)
163+
164+
Returns:
165+
dihedrals (array): set of dihedrals
166+
"""
167+
# Start with empty array
168+
dihedrals = []
169+
atom_groups = []
170+
171+
# if united atom level, read dihedrals from MDAnalysis universe
172+
if level == "united_atom":
173+
dihedrals = data_container.dihedrals
174+
num_dihedrals = len(dihedrals)
175+
for index in range(num_dihedrals):
176+
atom_groups.append(dihedrals[index].atoms)
177+
178+
# if residue level, looking for dihedrals involving residues
179+
if level == "residue":
180+
num_residues = len(data_container.residues)
181+
logger.debug(f"Number Residues: {num_residues}")
182+
if num_residues < 4:
183+
logger.debug("no residue level dihedrals")
184+
185+
else:
186+
# find bonds between residues N-3:N-2 and N-1:N
187+
for residue in range(4, num_residues + 1):
188+
# Using MDAnalysis selection,
189+
# assuming only one covalent bond between neighbouring residues
190+
# TODO not written for branched polymers
191+
atom_string = (
192+
"resindex "
193+
+ str(residue - 4)
194+
+ " and bonded resindex "
195+
+ str(residue - 3)
196+
)
197+
atom1 = data_container.select_atoms(atom_string)
198+
199+
atom_string = (
200+
"resindex "
201+
+ str(residue - 3)
202+
+ " and bonded resindex "
203+
+ str(residue - 4)
204+
)
205+
atom2 = data_container.select_atoms(atom_string)
206+
207+
atom_string = (
208+
"resindex "
209+
+ str(residue - 2)
210+
+ " and bonded resindex "
211+
+ str(residue - 1)
212+
)
213+
atom3 = data_container.select_atoms(atom_string)
214+
215+
atom_string = (
216+
"resindex "
217+
+ str(residue - 1)
218+
+ " and bonded resindex "
219+
+ str(residue - 2)
220+
)
221+
atom4 = data_container.select_atoms(atom_string)
222+
223+
atom_groups.append(atom1 + atom2 + atom3 + atom4)
224+
225+
logger.debug(f"Level: {level}, Dihedrals: {atom_groups}")
226+
227+
return atom_groups
228+
229+
def _identify_peaks(
230+
self,
231+
data_container,
232+
molecules,
233+
dihedrals,
234+
bin_width,
235+
start,
236+
end,
237+
step,
238+
):
239+
"""
240+
Build a histogram of the dihedral data and identify the peaks.
241+
This is to give the information needed for the adaptive method
242+
of identifying dihedral states.
243+
"""
244+
peak_values = [] * len(dihedrals)
245+
for dihedral_index in range(len(dihedrals)):
246+
phi = []
247+
# get the values of the angle for the dihedral
248+
# loop over all molecules in the averaging group
249+
# dihedral angle values have a range from -180 to 180
250+
for molecule in molecules:
251+
mol = UniverseOperations.get_molecule_container(
252+
data_container, molecule
253+
)
254+
number_frames = len(mol.trajectory)
255+
R = Dihedral(dihedrals).run()
256+
for timestep in range(number_frames):
257+
value = R.results.angles[timestep][dihedral_index]
258+
259+
# We want postive values in range 0 to 360 to make
260+
# the peak assignment.
261+
# works using the fact that dihedrals have circular symetry
262+
# (i.e. -15 degrees = +345 degrees)
263+
if value < 0:
264+
value += 360
265+
phi.append(value)
266+
267+
# create a histogram using numpy
268+
number_bins = int(360 / bin_width)
269+
popul, bin_edges = np.histogram(a=phi, bins=number_bins, range=(0, 360))
270+
bin_value = [
271+
0.5 * (bin_edges[i] + bin_edges[i + 1]) for i in range(0, len(popul))
272+
]
273+
274+
# identify "convex turning-points" and populate a list of peaks
275+
# peak : a bin whose neighboring bins have smaller population
276+
# NOTE might have problems if the peak is wide with a flat or
277+
# sawtooth top in which case check you have a sensible bin width
278+
279+
peaks = []
280+
for bin_index in range(number_bins):
281+
# if there is no dihedrals in a bin then it cannot be a peak
282+
if popul[bin_index] == 0:
283+
pass
284+
# being careful of the last bin
285+
# (dihedrals have circular symmetry, the histogram does not)
286+
elif (
287+
bin_index == number_bins - 1
288+
): # the -1 is because the index starts with 0 not 1
289+
if (
290+
popul[bin_index] >= popul[bin_index - 1]
291+
and popul[bin_index] >= popul[0]
292+
):
293+
peaks.append(bin_value[bin_index])
294+
else:
295+
if (
296+
popul[bin_index] >= popul[bin_index - 1]
297+
and popul[bin_index] >= popul[bin_index + 1]
298+
):
299+
peaks.append(bin_value[bin_index])
300+
301+
peak_values.append(peaks)
302+
303+
logger.debug(f"Dihedral: {dihedral_index}, Peak Values: {peak_values}")
304+
305+
return peak_values
306+
307+
def _assign_states(
308+
self,
309+
data_container,
310+
molecules,
311+
dihedrals,
312+
peaks,
313+
start,
314+
end,
315+
step,
316+
):
317+
"""
318+
Turn the dihedral values into conformations based on the peaks
319+
from the histogram.
320+
Then combine these to form states for each molecule.
321+
"""
322+
conformations = []
323+
states = []
324+
325+
# get the values of the angle for the dihedral
326+
# dihedral angle values have a range from -180 to 180
327+
for molecule in molecules:
328+
mol = UniverseOperations.get_molecule_container(data_container, molecule)
329+
number_frames = len(mol.trajectory)
330+
R = Dihedral(dihedrals).run()
331+
for dihedral_index in range(len(dihedrals)):
332+
conformation = []
333+
for timestep in range(number_frames):
334+
value = R.results.angles[timestep][dihedral_index]
335+
336+
# We want postive values in range 0 to 360 to make
337+
# the peak assignment.
338+
# works using the fact that dihedrals have circular symetry
339+
# (i.e. -15 degrees = +345 degrees)
340+
if value < 0:
341+
value += 360
342+
343+
# Find the turning point/peak that the snapshot is closest to.
344+
distances = [abs(value - peak) for peak in peaks[dihedral_index]]
345+
conformation.append(np.argmin(distances))
346+
347+
logger.debug(
348+
f"Dihedral: {dihedral_index} Conformations: {conformation}"
349+
)
350+
conformations.append(conformation)
351+
352+
# for all the dihedrals available concatenate the label of each
353+
# dihedral into the state for that frame
354+
mol_states = [
355+
state
356+
for state in (
357+
"".join(
358+
str(int(conformations[d][f])) for d in range(len(dihedrals))
359+
)
360+
for f in range(number_frames)
361+
)
362+
if state
363+
]
364+
365+
if states is None:
366+
states = mol_states
367+
else:
368+
states.extend(mol_states)
369+
370+
logger.debug(f"States: {states}")
371+
372+
return states

0 commit comments

Comments
 (0)