forked from jax-md/jax-md
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfire_minimization.py
More file actions
210 lines (162 loc) · 5.14 KB
/
fire_minimization.py
File metadata and controls
210 lines (162 loc) · 5.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# ---
# jupyter:
# jupytext:
# formats: py:percent,ipynb
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.18.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# [](https://jax-md.readthedocs.io/en/main/notebooks/minimization.ipynb)
# [](https://raw.githubusercontent.com/google/jax-md/main/examples/minimization.py)
# %% [markdown]
# # Harmonic Minimization
#
# Here we demonstrate some simple example code showing how we might find the inherent structure for some initially random configuration of particles. Note that this code will work on CPU, GPU, or TPU out of the box.
#
# First thing we need to do is set some parameters that define our simulation, including what kind of box we're using (specified using a metric function and a wrapping function).
# %% [markdown]
# ## Imports & Utils
# %%
import os
IN_COLAB = 'COLAB_RELEASE_TAG' in os.environ
if IN_COLAB:
import subprocess, sys
subprocess.run(
[
sys.executable,
'-m',
'pip',
'install',
'-q',
'git+https://github.com/jax-md/jax-md.git',
]
)
import numpy as onp
import jax.numpy as np
from jax import config
config.update('jax_enable_x64', True)
from jax import random
from jax import jit
from jax_md import space, smap, energy, minimize, quantity, simulate
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style(style='white')
def format_plot(x, y):
plt.grid(True)
plt.xlabel(x, fontsize=20)
plt.ylabel(y, fontsize=20)
def finalize_plot(shape=(1, 1)):
plt.gcf().set_size_inches(
shape[0] * 1.5 * plt.gcf().get_size_inches()[1],
shape[1] * 1.5 * plt.gcf().get_size_inches()[1],
)
plt.tight_layout()
# Check if running in ReadTheDocs environment
SMOKE_TEST = os.environ.get('READTHEDOCS', False)
# %% [markdown]
# ## System Setup
# %%
# Simulation parameters
N = 400 if SMOKE_TEST else 1000
dimension = 2
box_size = quantity.box_size_at_number_density(N, 0.8, dimension)
displacement, shift = space.periodic(box_size)
# %% [markdown]
# Next we need to generate some random positions as well as particle sizes.
# %%
key = random.PRNGKey(0)
# %%
R = box_size * random.uniform(key, (N, dimension), dtype=np.float32)
# The system ought to be a 50:50 mixture of two types of particles, one
# large and one small.
sigma = np.array([[1.0, 1.2], [1.2, 1.4]])
N_2 = int(N / 2)
species = np.where(np.arange(N) < N_2, 0, 1)
# %% [markdown]
# ## FIRE Minimization
#
# Then we need to construct our FIRE minimization function. Like all simulations in JAX MD, the FIRE optimizer is two functions: an `init_fn` that creates the state of the optimizer and an `apply_fn` that updates the state to a new state.
# %%
energy_fn = energy.soft_sphere_pair(displacement, species=species, sigma=sigma)
fire_init, fire_apply = minimize.fire_descent(energy_fn, shift)
fire_apply = jit(fire_apply)
fire_state = fire_init(R)
# %% [markdown]
# Now let's actually do minimization, keeping track of the energy and particle positions as we go.
# %%
E = []
trajectory = []
# Use fewer iterations for SMOKE_TEST
max_steps = 200
for i in range(max_steps):
fire_state = fire_apply(fire_state)
E += [energy_fn(fire_state.position)]
trajectory += [fire_state.position]
R = fire_state.position
trajectory = np.stack(trajectory)
# %% [markdown]
# ## Analysis
#
# Let's plot the nearest distance for different species pairs. We see that particles on average have neighbors that are the right distance apart.
# %%
metric = lambda R: space.distance(space.map_product(displacement)(R, R))
dr = metric(R)
plt.plot(
np.min(dr[:N_2, :N_2] + 5 * np.eye(N_2, N_2), axis=0),
'o',
label='$\\sigma_{AA}$',
)
plt.plot(
np.min(dr[:N_2, N_2:] + 5 * np.eye(N_2, N_2), axis=0),
'o',
label='$\\sigma_{AB}$',
)
plt.plot(
np.min(dr[N_2:, N_2:] + 5 * np.eye(N_2, N_2), axis=0),
'o',
label='$\\sigma_{BB}$',
)
plt.legend()
format_plot('', 'min neighbor distance')
finalize_plot()
# %% [markdown]
# Now let's plot the system. It's nice and minimized!
# %%
ms = 45
R_plt = onp.array(fire_state.position)
plt.plot(R_plt[:N_2, 0], R_plt[:N_2, 1], 'o', markersize=ms * 0.5)
plt.plot(R_plt[N_2:, 0], R_plt[N_2:, 1], 'o', markersize=ms * 0.7)
plt.xlim([0, np.max(R[:, 0])])
plt.ylim([0, np.max(R[:, 1])])
plt.axis('off')
finalize_plot((2, 2))
# %% [markdown]
# If we want, we can visualize the entire minimization.
# %%
if IN_COLAB:
from jax_md.colab_tools import renderer
diameter = np.where(species, 1.4, 1.0)
color = np.where(
species[:, None],
np.array([[1.0, 0.5, 0.05]]),
np.array([[0.15, 0.45, 0.8]]),
)
renderer.render(
box_size,
{'particles': renderer.Disk(trajectory, diameter, color)},
buffer_size=50,
)
# %% [markdown]
# Finally, let's plot the energy trajectory that we observed during FIRE minimization.
# %%
plt.plot(E, linewidth=3)
format_plot('step', '$E$')
finalize_plot()