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

started working on distance based probabilities #87

Merged
merged 33 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
6f532c2
started working on distance based probabilities
godenymarta May 3, 2023
cd81b49
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] May 3, 2023
bb5f999
save and load prob_function with update method
godenymarta May 4, 2023
418db6a
merge conflict
godenymarta May 4, 2023
cd30fa4
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] May 4, 2023
e4b8254
changed structure to work also when r_min not given
godenymarta May 4, 2023
22928ef
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] May 4, 2023
e361e9f
changed structure to work also when r_min not given
godenymarta May 4, 2023
8cf6f06
minor changes to print statements
godenymarta May 5, 2023
0378d5e
Merge branch 'main' of github.com:florianjoerg/protex into dist_prob
godenymarta May 5, 2023
795abd8
print statements for testing
godenymarta May 19, 2023
f1f2a0b
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] May 19, 2023
7da80cf
add __eq__ and __hash__ to Residue
florianjoerg May 19, 2023
0b507f9
Merge pull request #93 from florianjoerg/custom_residue_hash
florianjoerg Jun 5, 2023
ef312ca
Update residue.py
florianjoerg Jun 5, 2023
2596740
Merge branch 'main' into dist_prob to get updates
godenymarta Aug 8, 2023
5e4d7fb
added option to use barostat to im1h_oac_dummy_system
godenymarta Aug 8, 2023
ab88d5d
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Aug 8, 2023
17dabbd
small corrections to using a variable K and to the possibility of usi…
godenymarta Aug 10, 2023
216fb62
Merge branch 'dist_prob' of github.com:florianjoerg/protex into dist_…
godenymarta Aug 10, 2023
7f381a4
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Aug 10, 2023
be96597
changed factor in setting the new position of H so that the new bond …
godenymarta Aug 11, 2023
fa0d504
option to turn off reorient with KeepHUpdate (mainly for debugging)
godenymarta Aug 21, 2023
48935be
removed unnecessary variable definition
godenymarta Aug 22, 2023
7f95bc0
changed __eq__ and __hash__ to consieder only residue indices (histor…
godenymarta Aug 24, 2023
9e15a3d
Merge branch 'main' into dist_prob
godenymarta Sep 15, 2023
3de091e
updates to testsystems to work with d2oac
godenymarta Sep 22, 2023
cb70978
files for formic acid
godenymarta Oct 2, 2023
8e8ef01
testing formic acid
godenymarta Oct 11, 2023
ff7dd0c
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Oct 11, 2023
f99cb3c
changed syntax from barostat to ensemble, get boxl at every update if…
godenymarta Oct 25, 2023
c83fe0f
🛠️ [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Oct 25, 2023
4f30f12
small change in reorient: set new position of H to 90% of acceptor - …
godenymarta Oct 27, 2023
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
8 changes: 7 additions & 1 deletion protex/residue.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ def __init__(
def __str__(self) -> str:
return f"Residue {self.current_name}, {self.residue}"

def __eq__(self, other) -> bool:
return self.current_name == other.current_name and self.residue.index == other.residue.index

def __hash__(self):
return hash((self.current_name, self.residue.index))

@property
def has_equivalent_atom(self) -> bool:
"""Determines if the current residue has an equivalent atom defined.
Expand Down Expand Up @@ -500,7 +506,7 @@ def _get_offset(self, name, force_name=None):
def _get_offset_thole(self, name):
# get offset for atom idx for thole parameters
force_name = "DrudeForceThole"
print(self.parameters[name])
#print(self.parameters[name])
return min(
itertools.chain(
*[query_parm[0:2] for query_parm in self.parameters[name][force_name]]
Expand Down
8 changes: 7 additions & 1 deletion protex/testsystems.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ def setup_system(
dummy_atom_type: str = "DUMH",
cutoff: float = 11.0,
switch: float = 10.0,
barostat=None
):
if dummy_atom_type is not None:
# print(params.atom_types_str["DUM"].epsilon)
Expand Down Expand Up @@ -103,6 +104,10 @@ def setup_system(
print(
"Only contraints=None or constraints=HBonds (given as string in function call) implemented"
)


if barostat is not None:
system.addForce(barostat)

for force in system.getForces():
if type(force).__name__ == "CMMotionRemover":
Expand Down Expand Up @@ -630,6 +635,7 @@ def generate_im1h_oac_dummy_system(
dummy_atom_type: str = "DUMH",
dummies: list[tuple[str, str]] = [("IM1", "H7"), ("OAC", "H")],
use_plugin: bool = True,
barostat=None
):
"""Set up a solvated and parametrized system for IM1H/OAC."""
base = f"{protex.__path__[0]}/forcefield"
Expand All @@ -654,7 +660,7 @@ def generate_im1h_oac_dummy_system(
boxl=boxl,
)
system = setup_system(
psf, params, constraints=constraints, dummy_atom_type=dummy_atom_type
psf, params, constraints=constraints, dummy_atom_type=dummy_atom_type, barostat=barostat
)

simulation = setup_simulation(
Expand Down
66 changes: 47 additions & 19 deletions protex/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,14 @@ def __init__(
all_forces: bool,
include_equivalent_atom: bool,
reorient: bool,
K:int = 300,
) -> None:
self.ionic_liquid: ProtexSystem = ionic_liquid
self.to_adapt: list[tuple[str, int, frozenset[str]]] = to_adapt
self.include_equivalent_atom: bool = include_equivalent_atom
self.reorient: bool = reorient
self.all_forces: bool = all_forces
self.K = K
allowed_forces: list[str] = [ # change charges only
"NonbondedForce", # BUG: Charge stored in the DrudeForce does NOT get updated, probably you want to allow DrudeForce as well!
"CustomNonbondedForce", # NEW
Expand Down Expand Up @@ -102,7 +104,7 @@ def _update(self, candidates: list[tuple], nr_of_steps: int) -> None:
pass

def _adapt_probabilities(
self, to_adapt=list[tuple[str, int, frozenset[str]]]
self, to_adapt=list[tuple[str, int, frozenset[str]]], K=int
Copy link
Member

@florianjoerg florianjoerg Aug 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not add K to the function signature here. It is already accessible inside the class (as defined in line 65) via self.K. Just use self.K in line 146 for the factor variable

) -> None:
"""Adapt the probability for certain events depending on the current equilibrium, in order to stay close to a given reference
i.e. prob_neu = prob_orig + K*( x(t) - x(eq) )^3 where x(t) is the current percentage in the system of one species.
Expand All @@ -119,7 +121,7 @@ def _adapt_probabilities(
len([e for e, c in counts.items() if c > 1]) == 0
), "No duplicates for the transfer reactions allowed!"

K = 300

current_numbers: dict[
str, int
] = self.ionic_liquid.get_current_number_of_each_residue_type()
Expand Down Expand Up @@ -182,9 +184,10 @@ def __init__(
to_adapt: list[tuple[str, int, frozenset[str]]] or None = None,
include_equivalent_atom: bool = False,
reorient: bool = False,
K: int = 300
) -> None:
super().__init__(
ionic_liquid, to_adapt, all_forces, include_equivalent_atom, reorient
ionic_liquid, to_adapt, all_forces, include_equivalent_atom, reorient, K
)

def dump(self, fname: str) -> None:
Expand Down Expand Up @@ -216,9 +219,9 @@ def _reorient_atoms(self, candidate, positions, positions_copy):
)

pos_atom = positions_copy[atom_idx]
print(f"{pos_atom=}")
#print(f"{pos_atom=}")
pos_equivalent = positions_copy[equivalent_idx]
print(f"{pos_equivalent=}")
#print(f"{pos_equivalent=}")

positions[atom_idx] = pos_equivalent
positions[equivalent_idx] = pos_atom
Expand All @@ -237,9 +240,9 @@ def _reorient_atoms(self, candidate, positions, positions_copy):
# positions[atom_idx+6] = pos_equivalent_lp12
# positions[equivalent_idx+5] = pos_atom_lp21
# positions[equivalent_idx+6] = pos_atom_lp22
print(
f"setting position of {self.ionic_liquid.templates.get_atom_name_for(resi.current_name)} to {positions[atom_idx]} and {self.ionic_liquid.templates.get_equivalent_atom_for(resi.current_name)} to {positions[equivalent_idx]}"
)
# print(
# f"setting position of {self.ionic_liquid.templates.get_atom_name_for(resi.current_name)} to {positions[atom_idx]} and {self.ionic_liquid.templates.get_equivalent_atom_for(resi.current_name)} to {positions[equivalent_idx]}"
# )

# set new H position:
if "H" in self.ionic_liquid.templates.get_atom_name_for(
Expand Down Expand Up @@ -312,9 +315,9 @@ def _reorient_atoms(self, candidate, positions, positions_copy):
# update position of the once-dummy H on the acceptor - original H line
positions[idx_accepted_H] = pos_accepted_H

print(
f"donated H: {pos_donated_H}, acceptor atom: {pos_acceptor_atom}, H set to: {pos_accepted_H}"
)
# print(
# f"donated H: {pos_donated_H}, acceptor atom: {pos_acceptor_atom}, H set to: {pos_accepted_H}"
# )

return positions

Expand Down Expand Up @@ -373,10 +376,10 @@ def _update(self, candidates: list[tuple], nr_of_steps: int) -> None:

for candidate in candidates:
candidate1_residue, candidate2_residue = candidate
print(f"candidate pair {candidates.index(candidate)}")
print(
f"candidate1 used equivalent atom: {candidate1_residue.used_equivalent_atom}, candidate2 used equivalent atom: {candidate2_residue.used_equivalent_atom}"
)
#print(f"candidate pair {candidates.index(candidate)}")
# print(
# f"candidate1 used equivalent atom: {candidate1_residue.used_equivalent_atom}, candidate2 used equivalent atom: {candidate2_residue.used_equivalent_atom}"
# )

positions = self._reorient_atoms(candidate, positions, positions_copy)

Expand Down Expand Up @@ -571,13 +574,15 @@ def load(fname: str, updateMethod: Update) -> StateUpdate:
from_pickle = pickle.load(inp) # ensure correct order of arguments
state_update.history = from_pickle[0]
state_update.update_trial = from_pickle[1]
state_update.prob_function = from_pickle[2]
return state_update

def __init__(self, updateMethod: Update) -> None:
def __init__(self, updateMethod: Update, prob_function: str = None) -> None:
self.updateMethod: Update = updateMethod
self.ionic_liquid: ProtexSystem = self.updateMethod.ionic_liquid
self.history: deque = deque(maxlen=10)
self.update_trial: int = 0
self.prob_function = prob_function

def dump(self, fname: str) -> None:
"""Pickle the StateUpdate instance.
Expand All @@ -590,6 +595,7 @@ def dump(self, fname: str) -> None:
to_pickle = [
self.history,
self.update_trial,
self.prob_function
] # enusre correct order of arguments
with open(fname, "wb") as outp:
pickle.dump(to_pickle, outp, pickle.HIGHEST_PROTOCOL)
Expand Down Expand Up @@ -658,6 +664,7 @@ def _print_start(self):
##############################
##############################
--- Update trial: {self.update_trial} ---
{self.updateMethod.K=}
##############################
##############################
"""
Expand Down Expand Up @@ -706,7 +713,7 @@ def update(self, nr_of_steps: int = 2) -> list[tuple[Residue, Residue]]:
self.update_trial += 1

if self.updateMethod.to_adapt is not None:
self.updateMethod._adapt_probabilities(self.updateMethod.to_adapt)
self.updateMethod._adapt_probabilities(self.updateMethod.to_adapt, self.updateMethod.K)

self._print_stop()

Expand Down Expand Up @@ -736,6 +743,12 @@ def _rPBC(
dz = boxl - dz
return np.sqrt(dx * dx + dy * dy + dz * dz)

def distance_based_probability(r, r_min, r_max, prob):
if self.prob_function == "linear":
return -(prob/(r_max-r_min))*r+prob*r_max/(r_max-r_min)
elif self.prob_function == "cosine":
return (prob/2)*np.cos(np.pi/(r_max-r_min)*r-np.pi*r_min/(r_max-r_min))+prob/2

# calculate distance matrix between the two molecules
if use_pbc:
logger.debug("Using PBC correction for distance calculation")
Expand Down Expand Up @@ -774,12 +787,27 @@ def _rPBC(
prob = self.ionic_liquid.templates.allowed_updates[
frozenset([residue1.current_name, residue2.current_name])
]["prob"]
logger.debug(f"{r_max=}, {prob=}")
r = distance[candidate_idx1, candidate_idx2]
if self.prob_function is None:
dist_prob = prob
logger.debug(f"{r=}, {r_max=}, {prob=}")
else:
r_min = self.ionic_liquid.templates.allowed_updates[
frozenset([residue1.current_name, residue2.current_name])
]["r_min"]
if r < r_min:
dist_prob = prob
elif r <= r_max:
dist_prob = distance_based_probability(r, r_min, r_max, prob)
else:
dist_prob = 0
logger.debug(f"{r=}, {r_min=}, {r_max=}, {prob=}, {dist_prob=}, {self.prob_function=}")
#print(f"{r=}, {r_min=}, {r_max=}, {prob=}, {dist_prob=}, {self.prob_function=}")

# break for loop if no pair can fulfill distance condition
if r > self.ionic_liquid.templates.overall_max_distance:
break
elif r <= r_max and random.random() <= prob: # random enough?
elif r <= r_max and random.random() <= dist_prob: # random enough?
charge_candidate_idx1 = residue1.endstate_charge
charge_candidate_idx2 = residue2.endstate_charge

Expand Down