Skip to content

Commit

Permalink
refactor(recipe): make BondOperation and Place regular classes instead
Browse files Browse the repository at this point in the history
of dataclasses
  • Loading branch information
jmbuhr committed Mar 5, 2024
1 parent 0bebb47 commit 0bc1db3
Show file tree
Hide file tree
Showing 8 changed files with 180 additions and 65 deletions.
6 changes: 3 additions & 3 deletions src/kimmdy/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,9 @@ def radical_migration(
picked_recipes = {}
for recipes in run_dir.glob("*decide_recipe/recipes.csv"):
task_nr = int(recipes.parents[0].stem.split(sep="_")[0])
rc, picked_recipe = RecipeCollection.from_csv(recipes)
_, picked_recipe = RecipeCollection.from_csv(recipes)
picked_recipes[task_nr] = picked_recipe
sorted_recipes = [val for key, val in sorted(picked_recipes.items())]
sorted_recipes = [v for _, v in sorted(picked_recipes.items())]

for sorted_recipe in sorted_recipes:
connectivity_difference = {}
Expand Down Expand Up @@ -598,7 +598,7 @@ def reaction_participation(dir: str, open_plot: bool = False):
reaction_count = {"overall": 0}
for recipes in run_dir.glob("*decide_recipe/recipes.csv"):
# get picked recipe
rc, picked_rp = RecipeCollection.from_csv(recipes)
_, picked_rp = RecipeCollection.from_csv(recipes)
assert picked_rp, f"No picked recipe found in {recipes}."
# get involved atoms
reaction_atom_ids = set()
Expand Down
5 changes: 3 additions & 2 deletions src/kimmdy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,10 @@ def _validate(self, section: str = "config"):
)
name = self.out.name.split("_")
out_end = name[-1]
out_start = "_".join(name[:-1])
if out_end.isdigit():
self.out = self.out.with_name(f"{out_start}_{int(out_end)+1:03}")
self.out = self.out.with_name(
f"{'_'.join(name[:-1])}_{int(out_end)+1:03}"
)
else:
self.out = self.out.with_name(self.out.name + "_001")

Expand Down
22 changes: 11 additions & 11 deletions src/kimmdy/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,12 @@ def merge_dihedrals(
parameterizedB = None

# construct parameterized Dihedral
if parameterizedA and parameterizedB:
if parameterizedA is not None and parameterizedB is not None:
# same

assert type(parameterizedA) == Dihedral or type(parameterizedA) == DihedralType
assert type(parameterizedB) == Dihedral or type(parameterizedB) == DihedralType

dihedralmerge = Dihedral(
*dihedral_key,
funct=funct,
Expand All @@ -207,8 +211,9 @@ def merge_dihedrals(
c4=parameterizedB.c1,
c5=parameterizedB.periodicity,
)
elif parameterizedA:
elif parameterizedA is not None:
# breaking
assert type(parameterizedA) == Dihedral or type(parameterizedA) == DihedralType
dihedralmerge = Dihedral(
*dihedral_key,
funct=funct,
Expand All @@ -219,8 +224,9 @@ def merge_dihedrals(
c4="0.00",
c5=parameterizedA.periodicity,
)
elif parameterizedB:
elif parameterizedB is not None:
# binding
assert type(parameterizedB) == Dihedral or type(parameterizedB) == DihedralType
dihedralmerge = Dihedral(
*dihedral_key,
funct="9",
Expand All @@ -242,14 +248,10 @@ def merge_top_moleculetypes_slow_growth(
molA: MoleculeType,
molB: MoleculeType,
ff: FF,
focus_nr: Optional[list[str]] = None,
) -> MoleculeType:
"""Takes two Topologies and joins them for a smooth free-energy like parameter transition simulation"""
hyperparameters = {"morse_well_depth": 300} # [kJ mol-1]

# TODO:
# think about how to bring focus_nr into this

# atoms
for nr in molA.atoms.keys():
atomA = molA.atoms[nr]
Expand Down Expand Up @@ -520,9 +522,7 @@ def merge_top_moleculetypes_slow_growth(
return molB


def merge_top_slow_growth(
topA: Topology, topB: Topology, focus_nr: Optional[list[str]] = None
) -> Topology:
def merge_top_slow_growth(topA: Topology, topB: Topology) -> Topology:
"""Takes two Topologies and joins them for a smooth free-energy like parameter transition simulation.
Expand All @@ -531,7 +531,7 @@ def merge_top_slow_growth(

molA = topA.moleculetypes[REACTIVE_MOLECULEYPE]
molB = topB.moleculetypes[REACTIVE_MOLECULEYPE]
molB = merge_top_moleculetypes_slow_growth(molA, molB, topB.ff, focus_nr)
molB = merge_top_moleculetypes_slow_growth(molA, molB, topB.ff)

return topB

Expand Down
12 changes: 12 additions & 0 deletions src/kimmdy/kmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ def extrande_mod(
f"\t\texpected tau: {expected_tau}"
)

b = None
tau = None
l = None
t_max = None
for cr_boarders, cr_rates, cr_recipes in zip(
pairwise(boarders), rate_windows, recipe_windows
):
Expand Down Expand Up @@ -262,6 +266,9 @@ def extrande_mod(
if chosen_recipe is not None:
break

if None in [b, tau, l, t_max]:
logger.error(f"Extrande calculation failed, some variables are None.")

if chosen_recipe is None:
logger.info(
f"No reaction was chosen\naccepted: 0, rejected: {rejected}, extra: {n_extra}"
Expand Down Expand Up @@ -343,6 +350,8 @@ def extrande(
)

n_extra = 0
tau = None
l = None
while t < t_max:
crr_window_idx = np.searchsorted(boarders, t, side="right") - 1
# only 0 rates left -> skip to end
Expand Down Expand Up @@ -390,6 +399,9 @@ def extrande(
f"{n_extra} extra reactions performed during extrande KMC calculation. Try increasing tau_scale"
)

if None in [tau, l]:
logger.error(f"Extrande calculation failed, some variables are None.")

if chosen_recipe is None:
logger.info(
f"No reaction was chosen\naccepted: 0, rejected: 1, extra: {n_extra}"
Expand Down
16 changes: 8 additions & 8 deletions src/kimmdy/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,15 +524,15 @@ def read_distances_dat(distances_dat: Path) -> dict:
class JSONEncoder(json.JSONEncoder):
"""Encoder that enables writing JSONs with numpy types."""

def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
def default(self, o):
if isinstance(o, np.integer):
return int(o)
elif isinstance(o, np.floating):
return float(o)
elif isinstance(o, np.ndarray):
return o.tolist()
else:
return super(JSONEncoder, self).default(obj)
return super(JSONEncoder, self).default(o)


def write_json(
Expand Down
4 changes: 2 additions & 2 deletions src/kimmdy/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ def parameterize_topology(self, current_topology: Topology) -> Topology:
class BasicParameterizer(Parameterizer):
"""reconstruct base force field state"""

def parameterize_topology(self, current_topology: Topology) -> None:
def parameterize_topology(self, current_topology: Topology) -> Topology:
"""Do nothing,
all necessary actions should already have happened in bind_bond and break_bond of Topology
"""
pass
return current_topology
Loading

0 comments on commit 0bc1db3

Please sign in to comment.