-
Notifications
You must be signed in to change notification settings - Fork 0
/
diamond.jl
2241 lines (1969 loc) · 88.1 KB
/
diamond.jl
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Reversible simulation for neural network model of diamond
# See https://github.com/greener-group/rev-sim for setup instructions
# Licence is MIT
# An appropriate conda environment should be activated
# Use CUDA_VISIBLE_DEVICES to set the GPU to run on
# Occasionally runs into PyGIL error, a known issue with PythonCall
# See also https://github.com/tummfm/difftre/blob/main/diamond.ipynb
ENV["JULIA_CONDAPKG_BACKEND"] = "Null"
using Molly
using Enzyme
using PythonCall
using TimerOutputs
using Optimisers
using CairoMakie
using BSON
import Zygote
import AtomsCalculators
import SimpleCrystals
import ChainRulesCore
import ChainRulesCore.NoTangent
using Dates
using LinearAlgebra
using Random
using Statistics
using Test
const out_dir = (length(ARGS) >= 1 ? ARGS[1] : "train_diamond")
const pymod_custom_energy = pyimport("DiffTRe.custom_energy")
const pymod_custom_space = pyimport("DiffTRe.custom_space")
const pymod_jax_md = pyimport("jax_md")
const pymod_jax = pyimport("jax")
const pymod_optax = pyimport("optax")
const pymod_pickle = pyimport("pickle")
const py_load_configuration = pyimport("DiffTRe.io").load_configuration
const T = Float64
const n_atoms = 1000
const n_atoms_x3 = 3 * n_atoms
const atom_mass = T(12.011)
const side_length = T(1.784) # nm
const side_offset = T(1e-12)
const boundary = TriclinicBoundary(
SVector(side_length, zero(T) , zero(T) ),
SVector(side_offset, side_length, zero(T) ),
SVector(side_offset, side_offset, side_length),
)
const Ω = box_volume(boundary) # nm^3
const temp = T(298.0) # K
const β = inv(ustrip(u"kJ * mol^-1", Unitful.R * temp * u"K")) # kJ^-1 * mol
const init_params_sw = T[7.049556277, 0.6022245584, 1.80, 21.0, 1.20, 0.14, 200.0]
const n_params_sw = length(init_params_sw)
const c_target = [649788.6, 74674.51, 348079.53] # kJ * mol^-1 * nm^-3, GPa in Thaler2021
const conv_to_GPa = ustrip(u"GPa", one(T) * u"kJ * mol^-1 * nm^-3" / Unitful.Na)
const γσ = T(5e-8) # Loss weight stress, kJ^-2 * mol^2 * nm^6
const γc = T(1e-10) # Loss weight stiffness, kJ^-2 * mol^2 * nm^6
const stiff_av_weight = T(0.0) # Weighting on stiffness stress tensor terms
const to = TimerOutput()
coords_copy(sys, neighbors=nothing; kwargs...) = copy(sys.coords)
velocities_copy(sys, neighbors=nothing; kwargs...) = copy(sys.velocities)
function CoordCopyLogger(n_steps_log)
return GeneralObservableLogger(coords_copy, Array{SArray{Tuple{3}, T, 1, 3}, 1}, n_steps_log)
end
function VelocityCopyLogger(n_steps_log)
return GeneralObservableLogger(velocities_copy, Array{SArray{Tuple{3}, T, 1, 3}, 1}, n_steps_log)
end
const py_box_tensor = pymod_jax.numpy.array(pylist([
[side_length, zero(T) , zero(T) ],
[zero(T) , side_length, zero(T) ],
[zero(T) , zero(T) , side_length],
]))
const py_displacement = pymod_jax_md.space.periodic_general(py_box_tensor)[0]
const py_neighbor_fn = pymod_jax_md.partition.neighbor_list(
py_displacement,
pymod_jax.numpy.ones(3),
0.14 * 1.80,
dr_threshold=0.05,
capacity_multiplier=1.5,
disable_cell_list=pybuiltins.True,
)
const py_R_init_nofrac, _, py_box_init = py_load_configuration(gethostname() == "jgreener-lmb" ?
"/home/jgreener/soft/difftre/data/confs/Diamond.pdb" :
"/lmb/home/jgreener/soft/difftre/data/confs/Diamond.pdb")
const py_R_init = pymod_custom_space.scale_to_fractional_coordinates(py_R_init_nofrac, py_box_init)[0]
const py_neighbors_init = py_neighbor_fn(py_R_init)
const py_init_fn, py_GNN_energy = pymod_custom_energy.DimeNetPP_neighborlist(py_displacement,
py_R_init, py_neighbors_init, 0.2)
const py_GNN_energy_jit = pymod_jax.jit(py_GNN_energy)
const py_random_key = pymod_jax.random.PRNGKey(rand(Int32))
const py_model_init_key = pymod_jax.random.split(py_random_key, 2)[0]
struct GNNParams{P}
py_params::P # Py or Nothing
end
const pyscript_params = """
from haiku._src.data_structures import FlatMapping
global FlatMapping
def py_add_params(p1, p2):
p_sum = {}
assert p1.keys() == p2.keys()
for k in p1:
if type(p1[k]) is FlatMapping:
p_sum[k] = py_add_params(p1[k], p2[k])
else:
p_sum[k] = p1[k] + p2[k]
return FlatMapping(p_sum)
def py_multiply_params(p, y):
p_multiply = {}
for k in p:
if type(p[k]) is FlatMapping:
p_multiply[k] = py_multiply_params(p[k], y)
else:
p_multiply[k] = p[k] * y
return FlatMapping(p_multiply)
"""
const py_params_nt = pyexec(
@NamedTuple{py_add_params, py_multiply_params},
pyscript_params,
Main,
)
const py_add_params = py_params_nt.py_add_params
const py_multiply_params = py_params_nt.py_multiply_params
Base.:+(p1::GNNParams{Py}, p2::GNNParams{Py}) = GNNParams(py_add_params(p1.py_params, p2.py_params))
Base.:+(p1::GNNParams{Nothing}, p2::GNNParams{Nothing}) = GNNParams(nothing)
Base.:+(p1::GNNParams{Py}, p2::GNNParams{Nothing}) = p1
Base.:+(p1::GNNParams{Nothing}, p2::GNNParams{Py}) = p2
function Base.:*(p::GNNParams{Py}, y)
if y == 1
return p
else
return GNNParams(py_multiply_params(p.py_params, y))
end
end
Base.:*(p::GNNParams{Nothing}, y) = GNNParams(nothing)
gnn_example_array(py_params) = py_params["Energy/~/Output_3/~/Dense_Series_1"]["w"]
function Base.show(io::IO, p::GNNParams{Py})
# Show a representative set of parameters
rep_param = pyconvert(T, gnn_example_array(p.py_params).sum().item())
print(io, "GNNParams(", rep_param, ")")
end
Base.show(io::IO, ::GNNParams{Nothing}) = print(io, "GNNParams(nothing)")
struct DimeNetPP
params::GNNParams
end
const py_gnn_init_params = py_init_fn(py_model_init_key, py_R_init, neighbor=py_neighbors_init)
const gnn_init_params = GNNParams(py_gnn_init_params)
const pyscript_loss = """
# See https://github.com/tummfm/difftre/blob/main/diamond.ipynb
import jax
global jax
from jax_md import space
global space
from DiffTRe import custom_quantity
global custom_quantity
from functools import partial
global partial
global GNN_energy_global
GNN_energy_global = GNN_energy
def energy_fn_template(energy_params):
gnn_energy = partial(GNN_energy_global, energy_params)
def energy(R, neighbor, **dynamic_kwargs):
return gnn_energy(R, neighbor=neighbor, **dynamic_kwargs)
return energy
global energy_fn_template_global
energy_fn_template_global = energy_fn_template
def virial_stress_tensor(frac_position, mass, velocity, neighbor, energy_params, box_tensor):
energy_fn = energy_fn_template_global(energy_params)
energy_fn_without_kwargs = lambda R, neighbor, box_tensor: energy_fn(R, neighbor=neighbor, box=box_tensor)
R = frac_position # In unit box if fractional coordinates used
negative_forces, box_gradient = jax.grad(energy_fn_without_kwargs, argnums=[0, 2])(R, neighbor, box_tensor)
R = space.transform(box_tensor, R) # Transform back to real positions
force_contribution = jax.numpy.dot(negative_forces.T, R)
box_contribution = jax.numpy.dot(box_gradient.T, box_tensor)
virial_tensor = force_contribution + box_contribution
spatial_dim = frac_position.shape[-1]
volume = custom_quantity.box_volume(box_tensor, spatial_dim)
kinetic_tensor = custom_quantity.kinetic_energy_tensor(mass, velocity)
return (kinetic_tensor + virial_tensor) / volume
global virial_stress_tensor_global
virial_stress_tensor_global = virial_stress_tensor
def loss(frac_position, mass, velocity, neighbor, energy_params, box_tensor):
st = virial_stress_tensor_global(frac_position, mass, velocity, neighbor, energy_params, box_tensor)
return (st * st).sum() * $γσ / 9
py_loss_jit = jax.jit(loss)
def forces_sum(params, frac_coords, neighbors, box_tensor, d_fs):
fs = -jax.grad(jax.jit(GNN_energy_global), argnums=[1])(
params, frac_coords, neighbors, box=box_tensor)[0]
return (fs * d_fs).sum()
py_forces_sum_jit = jax.jit(forces_sum)
"""
const py_loss_nt = pyexec(
@NamedTuple{py_loss_jit, py_forces_sum_jit},
pyscript_loss,
Main,
(GNN_energy=py_GNN_energy,),
)
const py_loss_jit = py_loss_nt.py_loss_jit
const py_forces_sum_jit = py_loss_nt.py_forces_sum_jit
function svecs_to_jax_array(svec_arr)
return pymod_jax.numpy.array(reinterpret(T, svec_arr)).reshape(n_atoms, 3)
end
function forces_gnn(params, frac_coords, py_neighbors)
py_frac_coords = svecs_to_jax_array(frac_coords)
py_fs = -pymod_jax.grad(py_GNN_energy_jit, argnums=[1])(
params.py_params, py_frac_coords, py_neighbors, box=py_box_tensor)[0]
return SVector{3, T}.(eachrow(pyconvert(Matrix{T}, py_fs)))
end
function ChainRulesCore.rrule(::typeof(forces_gnn), params, frac_coords, py_neighbors)
Y = forces_gnn(params, frac_coords, py_neighbors)
function forces_gnn_pullback(d_fs)
py_frac_coords = svecs_to_jax_array(frac_coords)
py_d_fs = svecs_to_jax_array(d_fs)
py_dl_dp, py_dl_dfc = pymod_jax.grad(py_forces_sum_jit, argnums=[0, 1])(
params.py_params, py_frac_coords, py_neighbors, py_box_tensor, py_d_fs)
dl_dp = GNNParams(py_dl_dp)
dl_dfc = SVector{3, T}.(eachrow(pyconvert(Matrix{T}, py_dl_dfc)))
return NoTangent(), dl_dp, dl_dfc, NoTangent()
end
return Y, forces_gnn_pullback
end
function AtomsCalculators.forces(sys, inter::DimeNetPP; py_neighbors=nothing, kwargs...)
frac_coords = sys.coords ./ side_length
if isnothing(py_neighbors)
py_neighbors_used = Zygote.ignore() do
py_neighbor_fn(svecs_to_jax_array(frac_coords))
end
else
py_neighbors_used = py_neighbors
end
return forces_gnn(inter.params, frac_coords, py_neighbors_used)
end
function AtomsCalculators.potential_energy(sys, inter::DimeNetPP; py_neighbors=nothing, kwargs...)
frac_coords = sys.coords ./ side_length
if isnothing(py_neighbors)
py_neighbors_used = Zygote.ignore() do
py_neighbor_fn(svecs_to_jax_array(frac_coords))
end
else
py_neighbors_used = py_neighbors
end
E = potential_energy_gnn(inter.params, frac_coords, py_neighbors_used)
return E
end
function potential_energy_gnn(params, frac_coords, py_neighbors)
py_frac_coords = svecs_to_jax_array(frac_coords)
E = py_GNN_energy_jit(params.py_params, py_frac_coords, py_neighbors, box=py_box_tensor)
return pyconvert(T, E.item())
end
function ChainRulesCore.rrule(::typeof(potential_energy_gnn), params, frac_coords, py_neighbors)
Y = potential_energy_gnn(params, frac_coords, py_neighbors)
function potential_energy_gnn_pullback(dy)
py_frac_coords = svecs_to_jax_array(frac_coords)
py_dl_dp, py_dl_dfc = pymod_jax.grad(py_GNN_energy_jit, argnums=[0, 1])(
params.py_params, py_frac_coords, py_neighbors, box=py_box_tensor)
dl_dp = GNNParams(py_dl_dp) * dy
dl_dfc = SVector{3, T}.(eachrow(pyconvert(Matrix{T}, py_dl_dfc))) .* dy
return NoTangent(), dl_dp, dl_dfc, NoTangent()
end
return Y, potential_energy_gnn_pullback
end
struct StillingerWeber{T}
A::T
B::T
p::Int
q::Int
a::T
λ::T
γ::T
σ::T
ϵ::T
end
function Base.zero(::StillingerWeber{T}) where T
return StillingerWeber(zero(T), zero(T), 0, 0, zero(T), zero(T), zero(T), zero(T), zero(T))
end
function Base.:+(sw1::StillingerWeber, sw2::StillingerWeber)
StillingerWeber(
sw1.A + sw2.A,
sw1.B + sw2.B,
sw1.p + sw2.p,
sw1.q + sw2.q,
sw1.a + sw2.a,
sw1.λ + sw2.λ,
sw1.γ + sw2.γ,
sw1.σ + sw2.σ,
sw1.ϵ + sw2.ϵ,
)
end
function ChainRulesCore.rrule(T::Type{<:StillingerWeber}, xs...)
Y = T(xs...)
function StillingerWeber_pullback(Ȳ)
return NoTangent(), Ȳ.A, Ȳ.B, NoTangent(), NoTangent(), Ȳ.a, Ȳ.λ, Ȳ.γ, Ȳ.σ, Ȳ.ϵ
end
return Y, StillingerWeber_pullback
end
# Also modify the function below
function potential_energy_sw(sw, coords, boundary, neighbors)
A, B, p, q, a, λ, γ, σ, ϵ = sw.A, sw.B, sw.p, sw.q, sw.a, sw.λ, sw.γ, sw.σ, sw.ϵ
E = zero(T)
for ni in 1:length(neighbors)
i, j, ks = neighbors[ni]
rij = norm(vector(coords[i], coords[j], boundary))
r = rij / σ
if r < a
pe = ϵ * A * (B * inv(r^p) - inv(r^q)) * exp(inv(r - a))
E += pe
end
for k in ks
rij_trip = r
rik_trip = norm(vector(coords[i], coords[k], boundary)) / σ
rjk_trip = norm(vector(coords[j], coords[k], boundary)) / σ
if rij_trip < a && rik_trip < a
θ_jik = bond_angle(coords[j], coords[i], coords[k], boundary)
E += ϵ * λ * exp(γ * inv(rij_trip - a) + γ * inv(rik_trip - a)) * (cos(θ_jik) + T(1/3))^2
end
if rij_trip < a && rjk_trip < a
θ_ijk = bond_angle(coords[i], coords[j], coords[k], boundary)
E += ϵ * λ * exp(γ * inv(rij_trip - a) + γ * inv(rjk_trip - a)) * (cos(θ_ijk) + T(1/3))^2
end
if rik_trip < a && rjk_trip < a
θ_ikj = bond_angle(coords[i], coords[k], coords[j], boundary)
E += ϵ * λ * exp(γ * inv(rik_trip - a) + γ * inv(rjk_trip - a)) * (cos(θ_ikj) + T(1/3))^2
end
end
end
return E
end
# A copy of the above but inlined to avoid an Enzyme error
@inline function potential_energy_sw_inline(sw, coords, boundary, neighbors)
A, B, p, q, a, λ, γ, σ, ϵ = sw.A, sw.B, sw.p, sw.q, sw.a, sw.λ, sw.γ, sw.σ, sw.ϵ
E = zero(T)
for ni in 1:length(neighbors)
i, j, ks = neighbors[ni]
rij = norm(vector(coords[i], coords[j], boundary))
r = rij / σ
if r < a
pe = ϵ * A * (B * inv(r^p) - inv(r^q)) * exp(inv(r - a))
E += pe
end
for k in ks
rij_trip = r
rik_trip = norm(vector(coords[i], coords[k], boundary)) / σ
rjk_trip = norm(vector(coords[j], coords[k], boundary)) / σ
if rij_trip < a && rik_trip < a
θ_jik = bond_angle(coords[j], coords[i], coords[k], boundary)
E += ϵ * λ * exp(γ * inv(rij_trip - a) + γ * inv(rik_trip - a)) * (cos(θ_jik) + T(1/3))^2
end
if rij_trip < a && rjk_trip < a
θ_ijk = bond_angle(coords[i], coords[j], coords[k], boundary)
E += ϵ * λ * exp(γ * inv(rij_trip - a) + γ * inv(rjk_trip - a)) * (cos(θ_ijk) + T(1/3))^2
end
if rik_trip < a && rjk_trip < a
θ_ikj = bond_angle(coords[i], coords[k], coords[j], boundary)
E += ϵ * λ * exp(γ * inv(rik_trip - a) + γ * inv(rjk_trip - a)) * (cos(θ_ikj) + T(1/3))^2
end
end
end
return E
end
function ChainRulesCore.rrule(::typeof(potential_energy_sw), sw, coords, boundary, neighbors)
Y = potential_energy_sw(sw, coords, boundary, neighbors)
function potential_energy_sw_pullback(dy)
d_coords = zero(coords)
grads = autodiff(
Enzyme.Reverse,
potential_energy_sw,
Active,
Active(sw),
Duplicated(coords, d_coords),
Const(boundary),
Const(neighbors),
)[1]
d_sw = StillingerWeber(grads[1].A * dy, grads[1].B * dy, grads[1].p, grads[1].q,
grads[1].a * dy, grads[1].λ * dy, grads[1].γ * dy, grads[1].σ * dy,
grads[1].ϵ * dy)
return NoTangent(), d_sw, d_coords .* dy, NoTangent(), NoTangent()
end
return Y, potential_energy_sw_pullback
end
function forces_sw!(fs_chunks, sw, coords, boundary, neighbors, n_threads=Threads.nthreads())
A, B, p, q, a, λ, γ, σ, ϵ = sw.A, sw.B, sw.p, sw.q, sw.a, sw.λ, sw.γ, sw.σ, sw.ϵ
n_chunks = n_threads
PythonCall.GC.disable()
Threads.@threads for chunk_i in 1:n_chunks
@inbounds for ni in chunk_i:n_chunks:length(neighbors)
i, j, ks = neighbors[ni]
dr = vector(coords[i], coords[j], boundary)
rij = norm(dr)
r = rij / σ
if r < a
df_dr = -A * exp(inv(r - a)) * (B * p * inv(r^(p+1)) + (B * inv(r^p) - 1) * inv((r - a)^2))
f = -ϵ * df_dr * inv(σ)
fdr = f * dr / rij
fs_chunks[chunk_i][i] -= fdr
fs_chunks[chunk_i][j] += fdr
end
trip_cutoff = a * σ
trip_cutoff_2 = 2 * trip_cutoff
for k in ks
dr_ik = vector(coords[i], coords[k], boundary)
norm_dr_ik = norm(dr_ik)
(norm_dr_ik > trip_cutoff_2) && continue
dr_jk = vector(coords[j], coords[k], boundary)
norm_dr_jk = norm(dr_jk)
((norm_dr_ik < trip_cutoff) || (norm_dr_jk < trip_cutoff)) || continue
dr_ij, norm_dr_ij = dr, rij
ndr_ij, ndr_ik, ndr_jk = dr_ij / norm_dr_ij, dr_ik / norm_dr_ik, dr_jk / norm_dr_jk
dot_ij_ik, dot_ji_jk, dot_ki_kj = dot(dr_ij, dr_ik), dot(-dr_ij, dr_jk), dot(dr_ik, dr_jk)
rij_trip = r
rik_trip = norm_dr_ik / σ
rjk_trip = norm_dr_jk / σ
if rij_trip < a && rik_trip < a
cos_θ_jik = dot_ij_ik / (norm_dr_ij * norm_dr_ik)
exp_term = exp(γ * inv(rij_trip - a) + γ * inv(rik_trip - a))
cos_term = cos_θ_jik + T(1/3)
dh_term = λ * cos_term^2 * -γ * exp_term
dh_drij = inv((rij_trip - a)^2) * dh_term
dh_drik = inv((rik_trip - a)^2) * dh_term
dh_dcosθjik = 2 * λ * exp_term * cos_term
dcosθ_drj = (dr_ik * norm_dr_ij^2 - dr_ij * dot_ij_ik) / (norm_dr_ij^3 * norm_dr_ik)
dcosθ_drk = (dr_ij * norm_dr_ik^2 - dr_ik * dot_ij_ik) / (norm_dr_ik^3 * norm_dr_ij)
fj = -ϵ * (dh_drij * ndr_ij / σ + dh_dcosθjik * dcosθ_drj)
fk = -ϵ * (dh_drik * ndr_ik / σ + dh_dcosθjik * dcosθ_drk)
fs_chunks[chunk_i][i] -= fj + fk
fs_chunks[chunk_i][j] += fj
fs_chunks[chunk_i][k] += fk
end
if rij_trip < a && rjk_trip < a
cos_θ_ijk = dot_ji_jk / (norm_dr_ij * norm_dr_jk)
exp_term = exp(γ * inv(rij_trip - a) + γ * inv(rjk_trip - a))
cos_term = cos_θ_ijk + T(1/3)
dh_term = λ * cos_term^2 * -γ * exp_term
dh_drij = inv((rij_trip - a)^2) * dh_term
dh_drjk = inv((rjk_trip - a)^2) * dh_term
dh_dcosθijk = 2 * λ * exp_term * cos_term
dcosθ_dri = ( dr_jk * norm_dr_ij^2 + dr_ij * dot_ji_jk) / (norm_dr_ij^3 * norm_dr_jk)
dcosθ_drk = (-dr_ij * norm_dr_jk^2 - dr_jk * dot_ji_jk) / (norm_dr_jk^3 * norm_dr_ij)
fi = -ϵ * (dh_drij * -ndr_ij / σ + dh_dcosθijk * dcosθ_dri)
fk = -ϵ * (dh_drjk * ndr_jk / σ + dh_dcosθijk * dcosθ_drk)
fs_chunks[chunk_i][j] -= fi + fk
fs_chunks[chunk_i][i] += fi
fs_chunks[chunk_i][k] += fk
end
if rik_trip < a && rjk_trip < a
cos_θ_ikj = dot_ki_kj / (norm_dr_ik * norm_dr_jk)
exp_term = exp(γ * inv(rik_trip - a) + γ * inv(rjk_trip - a))
cos_term = cos_θ_ikj + T(1/3)
dh_term = λ * cos_term^2 * -γ * exp_term
dh_drik = inv((rik_trip - a)^2) * dh_term
dh_drjk = inv((rjk_trip - a)^2) * dh_term
dh_dcosθikj = 2 * λ * exp_term * cos_term
dcosθ_dri = (-dr_jk * norm_dr_ik^2 + dr_ik * dot_ki_kj) / (norm_dr_ik^3 * norm_dr_jk)
dcosθ_drj = (-dr_ik * norm_dr_jk^2 + dr_jk * dot_ki_kj) / (norm_dr_jk^3 * norm_dr_ik)
fi = -ϵ * (dh_drik * -ndr_ik / σ + dh_dcosθikj * dcosθ_dri)
fj = -ϵ * (dh_drjk * -ndr_jk / σ + dh_dcosθikj * dcosθ_drj)
fs_chunks[chunk_i][k] -= fi + fj
fs_chunks[chunk_i][i] += fi
fs_chunks[chunk_i][j] += fj
end
end
end
end
PythonCall.GC.enable()
return nothing
end
function forces_sw(sw, coords, boundary, neighbors, n_threads=Threads.nthreads())
fs_chunks = [zero(coords) for _ in 1:n_threads]
forces_sw!(fs_chunks, sw, coords, boundary, neighbors, n_threads)
return sum(fs_chunks)
end
function ChainRulesCore.rrule(::typeof(forces_sw), sw, coords, boundary, neighbors, n_threads)
Y = forces_sw(sw, coords, boundary, neighbors, n_threads)
function forces_sw_pullback(d_fs)
fs_chunks = [zero(coords) for _ in 1:n_threads]
d_fs_chunks = [copy(d_fs) for _ in 1:n_threads]
d_coords = zero(coords)
grads = autodiff(
Enzyme.Reverse,
forces_sw!,
Const,
Duplicated(fs_chunks, d_fs_chunks),
Active(sw),
Duplicated(coords, d_coords),
Const(boundary),
Const(neighbors),
Const(n_threads),
)[1]
return NoTangent(), grads[2], d_coords, NoTangent(), NoTangent(), NoTangent()
end
return Y, forces_sw_pullback
end
function AtomsCalculators.forces(sys, inter::StillingerWeber; neighbors,
n_threads=Threads.nthreads(), kwargs...)
return forces_sw(inter, sys.coords, sys.boundary, neighbors, n_threads)
end
function AtomsCalculators.potential_energy(sys, inter::StillingerWeber; neighbors, kwargs...)
E = potential_energy_sw(inter, sys.coords, sys.boundary, neighbors)
return E
end
# Differs from standard neighbor list by returning triples (i, j, k)
struct TripletNeighborFinder{D}
dist_cutoff_pair::D
dist_cutoff_triplet::D
n_steps::Int
end
function Molly.find_neighbors(sys,
nf::TripletNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0,
force_recompute::Bool=false;
n_threads::Integer=Threads.nthreads())
if !force_recompute && !iszero(step_n % nf.n_steps)
return current_neighbors
end
sqdist_cutoff_pair = nf.dist_cutoff_pair^2
sqdist_cutoff_triplet, sqdist_cutoff_triplet_2 = nf.dist_cutoff_triplet^2, (2 * nf.dist_cutoff_triplet)^2
n_chunks = n_threads
neighbors_list_chunks = [Tuple{Int32, Int32, Vector{Int32}}[] for _ in 1:n_chunks]
PythonCall.GC.disable()
Threads.@threads for chunk_i in 1:n_chunks
@inbounds for pi in chunk_i:n_chunks:Molly.n_atoms_to_n_pairs(n_atoms)
i, j = Molly.pair_index(n_atoms, pi)
dr_ij = vector(sys.coords[i], sys.coords[j], sys.boundary)
r2_ij = sum(abs2, dr_ij)
if r2_ij <= sqdist_cutoff_pair
third_atoms = Int32[]
for k in (j + 1):n_atoms
dr_ik = vector(sys.coords[i], sys.coords[k], sys.boundary)
r2_ik = sum(abs2, dr_ik)
(r2_ik < sqdist_cutoff_triplet_2) || continue
dr_jk = vector(sys.coords[j], sys.coords[k], sys.boundary)
r2_jk = sum(abs2, dr_jk)
if r2_ik < sqdist_cutoff_triplet || r2_jk < sqdist_cutoff_triplet
push!(third_atoms, k)
end
end
push!(neighbors_list_chunks[chunk_i], (i, j, third_atoms))
end
end
end
PythonCall.GC.enable()
neighbors_list = Tuple{Int32, Int32, Vector{Int32}}[]
for chunk_i in 1:n_chunks
append!(neighbors_list, neighbors_list_chunks[chunk_i])
end
return NeighborList(length(neighbors_list), neighbors_list)
end
const neighbor_finder_fwd = TripletNeighborFinder(0.6 , 0.35 , 10)
const neighbor_finder_rev = TripletNeighborFinder(0.504, 0.252, 1 )
function outer_products(vels)
out = zeros(T, n_atoms, 3, 3)
@inbounds for ai in 1:n_atoms
sv = vels[ai]
for i in 1:3, j in 1:3
out[ai, i, j] = sv[i] * sv[j]
end
end
return out
end
function mat_mul(Ft, R)
FtR = zeros(T, 3, 3)
@inbounds for i in 1:3, j in 1:3
s = zero(T)
for k in axes(Ft, 2)
s += Ft[i, k] * R[k, j]
end
FtR[i, j] = s
end
return FtR
end
@inline function scale_frac_coord(fc, boundary)
bv = boundary.basis_vectors
return SVector(
fc[1] * bv[1][1] + fc[2] * bv[2][1] + fc[3] * bv[3][1],
fc[1] * bv[1][2] + fc[2] * bv[2][2] + fc[3] * bv[3][2],
fc[1] * bv[1][3] + fc[2] * bv[2][3] + fc[3] * bv[3][3],
)
end
# Also modify the function below
function potential_energy_sw_frac_coords(sw, frac_coords, boundary, neighbors)
coords = zero(frac_coords)
for i in 1:n_atoms
coords[i] = scale_frac_coord(frac_coords[i], boundary)
end
return potential_energy_sw(sw, coords, boundary, neighbors)
end
# A copy of the above but inlined to avoid an Enzyme error
@inline function potential_energy_sw_frac_coords_inline(sw, frac_coords, boundary, neighbors)
coords = zero(frac_coords)
for i in 1:n_atoms
coords[i] = scale_frac_coord(frac_coords[i], boundary)
end
return potential_energy_sw_inline(sw, coords, boundary, neighbors)
end
function dU_dh(sw, coords, boundary, neighbors)
box_pe_grads = zeros(T, 9)
zt, ot = zero(T), one(T)
for i in 1:9
d_boundary = TriclinicBoundary{T, true, T, T}(
SVector(
SVector(i == 1 ? ot : zt, i == 2 ? ot : zt, i == 3 ? ot : zt),
SVector(i == 4 ? ot : zt, i == 5 ? ot : zt, i == 6 ? ot : zt),
SVector(i == 7 ? ot : zt, i == 8 ? ot : zt, i == 9 ? ot : zt),
),
zt, zt, zt, SVector(zt, zt, zt), zt, zt, zt, zt, zt,
)
frac_coords = coords ./ side_length
box_pe_grads[i] = autodiff_deferred(
Enzyme.Forward,
potential_energy_sw_frac_coords,
DuplicatedNoNeed,
Const(sw),
Const(frac_coords),
Duplicated(boundary, d_boundary),
Const(neighbors),
)[1]
end
return box_pe_grads
end
function loss_stress_gnn(sys)
frac_coords = sys.coords ./ side_length
py_neighbors = Zygote.ignore() do
py_neighbor_fn(svecs_to_jax_array(frac_coords))
end
params = sys.general_inters.gnn.params
return loss_stress_gnn(frac_coords, sys.velocities, py_neighbors, params)
end
function loss_stress_gnn(frac_coords, velocities, py_neighbors, params)
py_stress = py_loss_jit(
svecs_to_jax_array(frac_coords),
atom_mass,
svecs_to_jax_array(velocities),
py_neighbors,
params.py_params,
py_box_tensor,
)
return pyconvert(T, py_stress.item())
end
function ChainRulesCore.rrule(::typeof(loss_stress_gnn), frac_coords, velocities,
py_neighbors, params)
Y = loss_stress_gnn(frac_coords, velocities, py_neighbors, params)
function loss_stress_gnn_pullback(dy)
py_dl_dfc, py_dl_dv, py_dl_dp = pymod_jax.grad(py_loss_jit, argnums=[0, 2, 4])(
svecs_to_jax_array(frac_coords),
atom_mass,
svecs_to_jax_array(velocities),
py_neighbors,
params.py_params,
py_box_tensor,
)
dl_dfc = SVector{3, T}.(eachrow(pyconvert(Matrix{T}, py_dl_dfc))) .* dy
dl_dv = SVector{3, T}.(eachrow(pyconvert(Matrix{T}, py_dl_dv ))) .* dy
dl_dp = GNNParams(py_dl_dp) * dy
return NoTangent(), dl_dfc, dl_dv, NoTangent(), dl_dp
end
return Y, loss_stress_gnn_pullback
end
function virial_stress_tensor(sw, coords, velocities, boundary, atom_masses,
neighbors, vel_term=true)
thermal_excitation_velocity = velocities .- (mean(velocities),)
velocity_tensors = outer_products(thermal_excitation_velocity)
kinetic_tensor = -dropdims(sum(atom_masses .* velocity_tensors; dims=1); dims=1)
fs = forces_sw(sw, coords, boundary, neighbors)
Ft = reshape(reinterpret(T, fs), 3, :)
R = reshape(reinterpret(T, coords), 3, :)'
FtR = mat_mul(Ft, R)
bvs = boundary.basis_vectors
box_tensor_flat = [bvs[1]..., bvs[2]..., bvs[3]...]
box_pe_grads = dU_dh(sw, coords, boundary, neighbors)
# Triclinic 3x3 matrix is upper triangular
box_contribution = reshape(box_pe_grads, 3, 3)' * reshape(box_tensor_flat, 3, 3)
virial_tensor = -FtR .+ box_contribution
if vel_term
return (kinetic_tensor .+ virial_tensor) ./ Ω
else
return virial_tensor ./ Ω
end
end
function loss_stress_sw(sys, vel_term=true)
return loss_stress_sw(sys.general_inters.sw, sys.coords, sys.velocities, sys.boundary,
masses(sys), find_neighbors(sys), vel_term)
end
function loss_stress_sw(sw, coords, velocities, boundary, atom_masses, neighbors, vel_term)
σij = virial_stress_tensor(sw, coords, velocities, boundary, atom_masses, neighbors, vel_term)
return sum(abs2, σij) * γσ / 9
end
function ChainRulesCore.rrule(::typeof(loss_stress_sw), sw, coords, velocities, boundary,
atom_masses, neighbors, vel_term)
Y = loss_stress_sw(sw, coords, velocities, boundary, atom_masses, neighbors, vel_term)
function loss_stress_sw_pullback(dy)
d_coords = zero(coords)
d_velocities = zero(velocities)
grads = autodiff_deferred(
Enzyme.Reverse,
loss_stress_sw,
Active,
Active(sw),
Duplicated(coords, d_coords),
Duplicated(velocities, d_velocities),
Const(boundary),
Const(atom_masses),
Const(neighbors),
Const(vel_term),
)[1]
d_sw = StillingerWeber(grads[1].A * dy, grads[1].B * dy, grads[1].p, grads[1].q,
grads[1].a * dy, grads[1].λ * dy, grads[1].γ * dy, grads[1].σ * dy,
grads[1].ϵ * dy)
return NoTangent(), d_sw, d_coords .* dy, d_velocities .* dy, NoTangent(),
NoTangent(), NoTangent(), NoTangent()
end
return Y, loss_stress_sw_pullback
end
approx_stress_diag(loss_val_stress) = conv_to_GPa * sqrt((loss_val_stress / (γσ / 9)) / 3)
function potential_energy_sw_eps(sws, coords, boundary, neighbors, epsilon)
frac_coords = coords ./ side_length
zt, ot = zero(T), one(T)
bv, ep = boundary.basis_vectors, epsilon
boundary_eps = TriclinicBoundary{T, true, T, T}(
SVector(
SVector(
bv[1][1] * (ep[1, 1] + ot) + bv[1][2] * ep[2, 1] + bv[1][3] * ep[3, 1],
bv[1][1] * ep[1, 2] + bv[1][2] * (ep[2, 2] + ot) + bv[1][3] * ep[3, 2],
bv[1][1] * ep[1, 3] + bv[1][2] * ep[2, 3] + bv[1][3] * (ep[3, 3] + ot),
),
SVector(
bv[2][1] * (ep[1, 1] + ot) + bv[2][2] * ep[2, 1] + bv[2][3] * ep[3, 1],
bv[2][1] * ep[1, 2] + bv[2][2] * (ep[2, 2] + ot) + bv[2][3] * ep[3, 2],
bv[2][1] * ep[1, 3] + bv[2][2] * ep[2, 3] + bv[2][3] * (ep[3, 3] + ot),
),
SVector(
bv[3][1] * (ep[1, 1] + ot) + bv[3][2] * ep[2, 1] + bv[3][3] * ep[3, 1],
bv[3][1] * ep[1, 2] + bv[3][2] * (ep[2, 2] + ot) + bv[3][3] * ep[3, 2],
bv[3][1] * ep[1, 3] + bv[3][2] * ep[2, 3] + bv[3][3] * (ep[3, 3] + ot),
),
),
zt, zt, zt, boundary.reciprocal_size, zt, zt, zt, zt, zt,
)
return potential_energy_sw_frac_coords_inline(sws[1], frac_coords, boundary_eps, neighbors)
end
function dU_dϵ(sws, coords, boundary, neighbors, epsilon, i, j)
d_epsilon = zeros(T, 3, 3)
d_epsilon[i, j] = one(T)
return autodiff_deferred(
Enzyme.Forward,
potential_energy_sw_eps,
DuplicatedNoNeed,
Const(sws),
Const(coords),
Const(boundary),
Const(neighbors),
Duplicated(epsilon, d_epsilon),
)[1]
end
function dU_dϵ(sws, coords, boundary, neighbors, epsilon)
dU_dϵ_out = zeros(T, 3, 3)
for i in 1:3, j in 1:3
dU_dϵ_out[i, j] = dU_dϵ(sws, coords, boundary, neighbors, epsilon, i, j)
end
return dU_dϵ_out
end
function d2U_dϵ2(sws, coords, boundary, neighbors, epsilon)
d2U_dϵ2_out = zeros(T, 3, 3, 3, 3)
for i in 1:3, j in 1:3, k in 1:3, l in 1:3
d_epsilon = zeros(T, 3, 3)
d_epsilon[i, j] = one(T)
d2U_dϵ2_out[l, k, j, i] = autodiff_deferred(
Enzyme.Forward,
dU_dϵ,
DuplicatedNoNeed,
Const(sws),
Const(coords),
Const(boundary),
Const(neighbors),
Duplicated(epsilon, d_epsilon),
Const(k),
Const(l),
)[1]
end
return d2U_dϵ2_out
end
function loss_stiff_sw_p1(sys)
return loss_stiff_sw_p1([sys.general_inters.sw], sys.coords, sys.boundary, find_neighbors(sys))
end
function loss_stiff_sw_p1(sws, coords, boundary, neighbors)
p1 = zeros(T, 3, 3, 3, 3)
loss_stiff_sw_p1!(p1, sws, coords, boundary, neighbors)
return p1
end
function loss_stiff_sw_p1!(p1, sws, coords, boundary, neighbors)
epsilon = zeros(T, 3, 3) # No dims
born_stiffness = d2U_dϵ2(sws, coords, boundary, neighbors, epsilon) ./ Ω # kJ * mol^-1 * nm^-3
born_stress = dU_dϵ(sws, coords, boundary, neighbors, epsilon) ./ Ω # kJ * mol^-1 * nm^-3
born_stress_op = stiff_av_weight .* reshape(born_stress, 3, 3, 1, 1) .* reshape(born_stress, 1, 1, 3, 3) # kJ^2 * mol^-2 * nm^-6
p1 .= born_stiffness .- Ω .* β .* born_stress_op
return p1
end
function ChainRulesCore.rrule(::typeof(loss_stiff_sw_p1), sws, coords, boundary, neighbors)
Y = loss_stiff_sw_p1(sws, coords, boundary, neighbors)
function loss_stiff_sw_p1_pullback(d_p1)
p1 = zeros(T, 3, 3, 3, 3)
d_sws = zero.(sws)
d_coords = zero(coords)
autodiff(
Enzyme.Reverse,
loss_stiff_sw_p1!,
Const,
Duplicated(p1, d_p1),
Duplicated(sws, d_sws),
Duplicated(coords, d_coords),
Const(boundary),
Const(neighbors),
)
return NoTangent(), d_sws, d_coords, NoTangent(), NoTangent()
end
return Y, loss_stiff_sw_p1_pullback
end
function loss_stiff_sw_p2(sys)
return loss_stiff_sw_p2([sys.general_inters.sw], sys.coords, sys.boundary, find_neighbors(sys))
end
function loss_stiff_sw_p2(sws, coords, boundary, neighbors)
p2 = zeros(T, 3, 3)
loss_stiff_sw_p2!(p2, sws, coords, boundary, neighbors)
return p2
end
function loss_stiff_sw_p2!(p2, sws, coords, boundary, neighbors)
epsilon = zeros(T, 3, 3) # No dims
p2 .= stiff_av_weight .* dU_dϵ(sws, coords, boundary, neighbors, epsilon) ./ Ω # kJ * mol^-1 * nm^-3
return p2
end
function ChainRulesCore.rrule(::typeof(loss_stiff_sw_p2), sws, coords, boundary, neighbors)
Y = loss_stiff_sw_p2(sws, coords, boundary, neighbors)
function loss_stiff_sw_p2_pullback(d_p2)
p2 = zeros(T, 3, 3)
d_sws = zero.(sws)
d_coords = zero(coords)
autodiff(
Enzyme.Reverse,
loss_stiff_sw_p2!,
Const,
Duplicated(p2, d_p2),
Duplicated(sws, d_sws),
Duplicated(coords, d_coords),
Const(boundary),
Const(neighbors),
)
return NoTangent(), d_sws, d_coords, NoTangent(), NoTangent()
end
return Y, loss_stiff_sw_p2_pullback
end
const pyscript_stiff = """
import jax
global jax
from functools import partial
global partial
global GNN_energy_global
GNN_energy_global = GNN_energy
global β_global
β_global = β
global volume_global
volume_global = volume
def energy_fn_template(energy_params):
gnn_energy = partial(GNN_energy_global, energy_params)
def energy(R, neighbor, **dynamic_kwargs):
return gnn_energy(R, neighbor=neighbor, **dynamic_kwargs)
return energy
global energy_fn_template_global
energy_fn_template_global = energy_fn_template
def energy_under_strain(epsilon, energy_fn, frac_coords, neighbor, box_tensor):
strained_box = jax.numpy.dot(box_tensor, jax.numpy.eye(3) + epsilon)
energy = energy_fn(frac_coords, neighbor=neighbor, box=strained_box)
return energy