-
Notifications
You must be signed in to change notification settings - Fork 10
feat(lattice): Make lattice geometries differentiable and backend-agn… #30
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
Merged
refraction-ray
merged 17 commits into
tensorcircuit:master
from
Stellogic:feature/lattice-updates
Aug 16, 2025
+2,212
−545
Merged
Changes from 2 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
9e01be8
feat(lattice): Make lattice geometries differentiable and backend-agn…
Stellogic 9d22384
fix mypy errors
Stellogic d71d4a1
delete all the debug log
Stellogic bb65592
fix according to the review
Stellogic 0ad707c
fix black
Stellogic 92bc8e4
fix black
Stellogic efaee05
fix mypy errors
Stellogic 7063c6f
fix test_backends.py
Stellogic 0660abf
Merge remote-tracking branch 'upstream/master' into feature/lattice-u…
Stellogic 589763e
fix black
Stellogic daa3ff2
fix according to the review
Stellogic 9575be5
fix according to the review
Stellogic d372f72
update lattice_neighbor_time_compare.py to enhance the accuracy
Stellogic 0b38522
fix black
Stellogic 04aca93
fix according to the review
Stellogic 283e1fd
fix according to the review
Stellogic 494a99b
fix black
Stellogic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
import optax | ||
import numpy as np | ||
import jax.numpy as jnp | ||
import matplotlib.pyplot as plt | ||
import jax | ||
import tensorcircuit as tc | ||
|
||
|
||
jax.config.update("jax_enable_x64", True) | ||
refraction-ray marked this conversation as resolved.
Show resolved
Hide resolved
|
||
K = tc.set_backend("jax") | ||
|
||
|
||
def calculate_potential(log_a, base_distance_matrix, epsilon=0.5, sigma=1.0): | ||
""" | ||
Calculate the total Lennard-Jones potential energy for a given logarithm of the lattice constant (log_a). | ||
""" | ||
lattice_constant = jnp.exp(log_a) | ||
refraction-ray marked this conversation as resolved.
Show resolved
Hide resolved
|
||
d = base_distance_matrix * lattice_constant | ||
d_safe = jnp.where(d > 1e-9, d, 1e-9) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. use K throughout, instead of mix usage of jax and K? |
||
|
||
term12 = (sigma / d_safe) ** 12 | ||
term6 = (sigma / d_safe) ** 6 | ||
potential_matrix = 4 * epsilon * (term12 - term6) | ||
|
||
num_sites = d.shape[0] | ||
potential_matrix = potential_matrix * ( | ||
1 - K.eye(num_sites, dtype=potential_matrix.dtype) | ||
) | ||
|
||
potential_energy = K.sum(potential_matrix) / 2.0 | ||
|
||
return potential_energy | ||
|
||
|
||
# Pre-calculate the base distance matrix (for lattice_constant=1.0) | ||
size = (10, 10) | ||
lat_base = tc.templates.lattice.SquareLattice(size, lattice_constant=1.0, pbc=True) | ||
base_distance_matrix = lat_base.distance_matrix | ||
|
||
# Create a lambda function to pass the base distance matrix to the potential function | ||
potential_fun_for_grad = lambda log_a: calculate_potential(log_a, base_distance_matrix) | ||
value_and_grad_fun = K.jit(K.value_and_grad(potential_fun_for_grad)) | ||
|
||
optimizer = optax.adam(learning_rate=0.01) | ||
|
||
log_a = K.convert_to_tensor(jnp.log(1.1)) | ||
|
||
opt_state = optimizer.init(log_a) | ||
|
||
history = {"a": [], "energy": []} | ||
|
||
print("Starting optimization of lattice constant...") | ||
for i in range(200): | ||
energy, grad = value_and_grad_fun(log_a) | ||
|
||
history["a"].append(jnp.exp(log_a)) | ||
history["energy"].append(energy) | ||
|
||
if jnp.isnan(grad): | ||
print(f"Gradient became NaN at iteration {i+1}. Stopping optimization.") | ||
print(f"Current energy: {energy}, Current log_a: {log_a}") | ||
break | ||
|
||
updates, opt_state = optimizer.update(grad, opt_state) | ||
log_a = optax.apply_updates(log_a, updates) | ||
|
||
if (i + 1) % 20 == 0: | ||
current_a = jnp.exp(log_a) | ||
print( | ||
f"Iteration {i+1}/200: Total Energy = {energy:.4f}, Lattice Constant = {current_a:.4f}" | ||
) | ||
|
||
final_a = jnp.exp(log_a) | ||
final_energy = calculate_potential(K.convert_to_tensor(log_a), base_distance_matrix) | ||
|
||
if not jnp.isnan(final_energy): | ||
print("\nOptimization finished!") | ||
print(f"Final optimized lattice constant: {final_a:.6f}") | ||
print(f"Corresponding minimum total energy: {final_energy:.6f}") | ||
|
||
# Vectorized calculation for the potential curve | ||
a_vals = np.linspace(0.8, 1.5, 200) | ||
log_a_vals = np.log(a_vals) | ||
|
||
# Use vmap to create a vectorized version of the potential function | ||
vmap_potential = jax.vmap(lambda la: calculate_potential(la, base_distance_matrix)) | ||
potential_curve = vmap_potential(K.convert_to_tensor(log_a_vals)) | ||
|
||
plt.figure(figsize=(10, 6)) | ||
plt.plot(a_vals, potential_curve, label="Lennard-Jones Potential", color="blue") | ||
plt.scatter( | ||
history["a"], | ||
history["energy"], | ||
color="red", | ||
s=20, | ||
zorder=5, | ||
label="Optimization Steps", | ||
) | ||
plt.scatter( | ||
final_a, | ||
final_energy, | ||
color="green", | ||
s=100, | ||
zorder=6, | ||
marker="*", | ||
label="Final Optimized Point", | ||
) | ||
|
||
plt.title("Lennard-Jones Potential Optimization") | ||
plt.xlabel("Lattice Constant (a)") | ||
plt.ylabel("Total Potential Energy") | ||
plt.legend() | ||
plt.grid(True) | ||
plt.show() | ||
else: | ||
print("\nOptimization failed. Final energy is NaN.") | ||
refraction-ray marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.