-
Notifications
You must be signed in to change notification settings - Fork 12
/
eval.py
322 lines (289 loc) · 9.92 KB
/
eval.py
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""
## Script for evaluating the ICSG3D reconstructions
## Example:
## >> python3 eval.py --name heusler --samples 5000
## Plots the reconstructed lattice params and EMD of atomic sites
--------------------------------------------------
## Author: Callum J. Court.
## Email: [email protected]
## Version: 1.0.0
--------------------------------------------------
## License: MIT
## Copyright: Copyright Callum Court & Batuhan Yildirim 2020, ICSG3D
-------------------------------------------------
"""
import argparse
import os
import re
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
from unet.unet import AtomUnet
from utils import (
create_crystal,
data_split,
get_sites,
to_lattice_params,
to_voxel_params,
)
from vae.data import VAEDataGenerator
from vae.lattice_vae import LatticeDFCVAE
from watershed import watershed_clustering
font = {"family": "serif"}
rc("font", **font)
rc("text", usetex=True)
rc("text.latex", preamble=r"\usepackage{cmbright}")
def emd(x, y):
"""
Computes the Earth Mover Distance between two point sets
--------------------------------------------------------
params: point sets x and y (N x M)
"""
dist = cdist(x, y)
assign = linear_sum_assignment(dist)
return dist[assign].sum() / min(len(x), len(y))
if __name__ == "__main__":
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument("--name", metavar="name", type=str, help="Name of data folder")
parser.add_argument(
"--batch_size", metavar="batch_size", type=int, help="Batch size", default=10
)
parser.add_argument(
"--samples",
metavar="samples",
type=int,
help="Number of samples",
default=78750,
)
parser.add_argument(
"--eps_frac",
metavar="eps_frac",
type=float,
help="Eps of lattice vector",
default=0.25,
)
parser.add_argument(
"--ncond",
metavar="ncond",
type=int,
help="Number of condition bins",
default=10,
)
parser.add_argument(
"--clus_iters",
metavar="clus_iters",
type=int,
help="Number of iterations for watershed clustering",
default=5,
)
parser.add_argument(
"--split",
metavar="split",
type=float,
help="Train-test split fraction",
default=0.8,
)
parser.add_argument(
"--d",
metavar="d",
type=int,
help="Dimension of density matrices (number of voxels)",
default=32,
)
namespace = parser.parse_args()
mode = namespace.name
ncond = namespace.ncond
data_path = os.path.join("data", mode, "matrices")
cif_path = os.path.join("data", mode, "cifs")
csv_path = os.path.join("data", mode, mode + ".csv")
d = namespace.d
input_shape = (d, d, d, 4)
n = namespace.samples
batch_size = namespace.batch_size
eps = namespace.eps_frac
vae_weights = os.path.join(
"saved_models", "vae", mode, "vae_weights_" + mode + ".best.hdf5"
)
unet_weights = os.path.join(
"saved_models", "unet", mode, "unet_weights_" + mode + ".best.hdf5"
)
perceptual_model = os.path.join(
"saved_models", "unet", mode, "unet_weights_" + mode + ".best.h5"
)
clustering_max_iters = namespace.clus_iters
os.makedirs(os.path.join("output", "eval", mode), exist_ok=True)
# Split the data
training_ids, validation_ids = data_split(
data_path, n, frac=namespace.split, n_rot=0
)
validation_generator = VAEDataGenerator(
validation_ids,
data_path=data_path,
property_csv=csv_path,
batch_size=batch_size,
n_channels=input_shape[-1],
shuffle=False,
n_bins=ncond,
)
# Create the VAE
vae = LatticeDFCVAE(perceptual_model=perceptual_model, cond_shape=ncond)
vae._set_model(weights=vae_weights, batch_size=batch_size)
# Create the Unet
unet = AtomUnet(weights=unet_weights)
true_num_atoms = []
pred_num_atoms = []
true_species = []
pred_species = []
true_lc = []
pred_lc = []
true_coords = []
pred_coords = []
emds = []
c = 0
for M, cond in validation_generator: # Density matrix, condition
# Get the reconstruction
M_prime = vae.model.predict([M, cond])
coords_prime = M_prime[:, :, :, :, 1:]
# Compute the reconstructed species matrix
S_prime, S_b_prime = unet.model.predict(M_prime)
S_prime = np.argmax(S_prime, axis=-1).reshape(batch_size, 32, 32, 32, 1)
S_b_prime[S_b_prime >= 0.8] = 1.0
S_b_prime[S_b_prime < 0.8] = 0.0
S_prime_coords = np.concatenate([S_prime, coords_prime], axis=-1)
# Calculate reconstructed lattice params
l_pred = to_lattice_params(coords_prime)
# Reconstructed voxel params
dv_pred = to_voxel_params(l_pred)
ids = validation_generator.list_IDs_temp
for i, S_prime_i in enumerate(S_prime_coords):
print(ids[i])
# True data
true_id = ids[i]
crystal = create_crystal(
os.path.join(cif_path, re.split("_|\.", true_id)[0] + ".cif"),
primitive=False,
)
N, z, r = get_sites(crystal)
lpt = [crystal.lattice.a, crystal.lattice.b, crystal.lattice.c]
N = np.multiply(N, lpt[:3])
dist = np.linalg.norm(N, ord=2, axis=1)
N = N[np.argsort(dist)]
# Predicted
try:
species, mu = watershed_clustering(
M_prime[i, :, :, :, 0], S_prime[i], S_b_prime[i]
)
except Exception:
print(ids[i], "failed")
continue
for s in N:
true_coords.append(s)
true_lc.append(lpt)
true_num_atoms.append(len(N))
true_species.append(np.unique(z))
pred_lc.append(l_pred[i])
lpp = eps * l_pred[i, :3].reshape(1, 3)
mu = mu * dv_pred[i] - (lpp) + (dv_pred[i] / 2.0)
dist = np.linalg.norm(mu, ord=2, axis=1)
mu = mu[np.argsort(dist)]
dist = emd(mu, N)
emds.append(dist)
# sort pred coords by dist from 0
pred_num_atoms.append(len(species))
pred_species.append(np.unique(species))
c += 1
true_num_atoms = np.array(true_num_atoms)
pred_num_atoms = np.array(pred_num_atoms)
true_lc = np.array(true_lc)
pred_lc = np.array(pred_lc)
print("\nMEAN EMD: ", np.mean(emds))
print("\nMEAN DAtoms: ", np.mean(np.abs(true_num_atoms - pred_num_atoms)))
# Plots
plt.figure()
plt.hist(emds, bins=50, color="tab:cyan")
plt.axvline(
x=np.mean(emds), linestyle="--", color="r", label="Mean = %.3f" % np.mean(emds)
)
plt.xlabel("EMD (Angstrom)")
plt.ylabel("Count")
plt.legend(loc="best")
plt.savefig(os.path.join("output", "eval" + mode + "emd.svg"), format="svg")
plt.close()
plt.figure()
plt.hist(np.abs(true_lc - pred_lc)[:, 0], bins=50, color="tab:cyan")
plt.axvline(
x=np.mean(np.abs(true_lc - pred_lc)[:, 0]),
linestyle="--",
color="tab:red",
label="Mean = %.3f" % np.mean(np.abs(true_lc - pred_lc)[:, 0]),
)
plt.xlabel("$|a_{true}$ - $a_{pred}|$ (Angstrom)")
plt.ylabel("Count")
plt.legend(loc="best")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_a.svg"), format="svg")
plt.close()
plt.figure()
plt.hist(np.abs(true_lc - pred_lc)[:, 1], bins=50, color="tab:cyan")
plt.axvline(
x=np.mean(np.abs(true_lc - pred_lc)[:, 1]),
linestyle="--",
color="tab:red",
label="Mean = %.3f" % np.mean(np.abs(true_lc - pred_lc)[:, 1]),
)
plt.xlabel("$|b_{true}$ - $b_{pred}|$ (Angstrom)")
plt.ylabel("Count")
plt.legend(loc="best")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_b.svg"), format="svg")
plt.close()
plt.figure()
plt.hist(np.abs(true_lc - pred_lc)[:, 2], bins=50, color="tab:cyan")
plt.axvline(
x=np.mean(np.abs(true_lc - pred_lc)[:, 2]),
linestyle="--",
color="tab:red",
label="Mean = %.3f" % np.mean(np.abs(true_lc - pred_lc)[:, 2]),
)
plt.xlabel("$|c_{true}$ - $c_{pred}|$ (Angstrom)")
plt.ylabel("Count")
plt.legend(loc="best")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_c.svg"), format="svg")
plt.close()
plt.figure()
plt.hist(np.abs(true_num_atoms - pred_num_atoms), bins=50, color="tab:cyan")
plt.axvline(
x=np.mean(np.abs(true_num_atoms - pred_num_atoms)),
linestyle="--",
color="tab:red",
label="Mean = %.3f" % np.mean(np.abs(true_num_atoms - pred_num_atoms)),
)
plt.xlim(0, 10)
plt.xlabel("$N_{true}$ - $N_{pred}$")
plt.ylabel("Count")
plt.legend(loc="best")
plt.savefig(os.path.join("output", "eval" + mode + "atoms.svg"), format="svg")
plt.close()
x = np.linspace(0, 10, 100)
plt.figure()
plt.scatter(true_lc[:, 0], pred_lc[:, 0], alpha=0.2, color="black")
plt.plot(x, x, "r--")
plt.xlabel("$a$ True (Angstrom)")
plt.ylabel("$a$ Pred (Angstrom)")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_a_tp.svg"), format="svg")
plt.close()
plt.figure()
plt.scatter(true_lc[:, 1], pred_lc[:, 1], alpha=0.2, color="black")
plt.plot(x, x, "r--")
plt.xlabel("$b$ True (Angstrom)")
plt.ylabel("$b$ Pred (Angstrom)")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_b_tp.svg"), format="svg")
plt.close()
plt.figure()
plt.scatter(true_lc[:, 2], pred_lc[:, 2], alpha=0.2, color="black")
plt.plot(x, x, "r--")
plt.xlabel("$c$ True (Angstrom)")
plt.ylabel("$c$ Pred (Angstrom)")
plt.savefig(os.path.join("output", "eval" + mode + "lattice_c_tp.svg"), format="svg")
plt.close()