Skip to content

Conversation

@Stellogic
Copy link
Contributor

This pull request implements Task 1 of the follow-up plan, introducing utility functions to generate common spin Hamiltonians from Lattice objects.

Key Contributions:

  • generate_heisenberg_hamiltonian: Creates a sparse Heisenberg Hamiltonian based on the nearest-neighbor pairs provided by the lattice.
  • generate_rydberg_hamiltonian: Creates a sparse Rydberg Hamiltonian, utilizing the lattice's distance matrix to calculate long-range interactions.
  • Comprehensive Tests: Added a new test file (tests/templates/test_hamiltonians.py) with unit tests that verify:
    • Scientific correctness against manually calculated small systems.
    • Robustness against edge cases (empty lattice, single site, zero distance).
    • Fundamental physical properties (e.g., Hermiticity).

@codecov
Copy link

codecov bot commented Jul 24, 2025

Codecov Report

❌ Patch coverage is 95.94595% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
tensorcircuit/templates/hamiltonians.py 95.94% 3 Missing ⚠️
Files with missing lines Coverage Δ
tensorcircuit/templates/hamiltonians.py 95.94% <95.94%> (ø)

... and 11 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

"""
Test properties of a larger lattice (2x2 square) without full matrix comparison.
"""
lattice = SquareLattice(size=(2, 2), pbc=True) # 4 sites, 8 bonds with PBC
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2*2 with PBC is subtle, as you can see, there will be two bonds between the same two lattice points

@refraction-ray
Copy link
Member

over all looks good, a nice work, only some minor details require fix or explanantion

This commit refactors the hamiltonian generation functions to be more robust, flexible, and aligned with the project's backend-agnostic architecture, based on feedback from the recent code review.

Key changes include:

- **Backend Agnosticism:**
  The `PauliStringSum2COO` call now uses `numpy=False`, ensuring the returned sparse matrix is a native tensor of the currently active backend (TensorFlow, JAX, etc.). The return type hints have been updated to `Any` to reflect this.

- **Anisotropic Heisenberg Model:**
  The `heisenberg_hamiltonian` function now accepts a list or tuple for `j_coupling`, allowing for the definition of anisotropic models with different Jx, Jy, and Jz values.

- **Test Suite Enhancement:**
  Tests have been updated to use `tc.backend.to_dense` for backend-agnostic validation. A new test case for the anisotropic Heisenberg model has also been added to ensure its correctness.

- **Code Cleanup:**
  A redundant `float()` cast was removed from the Rydberg hamiltonian logic.
from typing import Any, List, Tuple, Union
import numpy as np
from tensorcircuit.cons import dtypestr, backend
import tensorcircuit as tc
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont directly use tensorcircuit internally, use from .cons import dtypestr, backend and use backend.blah in the code instead of tc.backend

Internal API Usage: I've switched to importing backend and dtypestr from .cons and PauliStringSum2COO from ..quantum as you suggested, avoiding direct calls to the top-level tc package.
Error Handling: For both heisenberg_hamiltonian and rydberg_hamiltonian, I've added a check to raise a ValueError if num_sites is 0, which is indeed more explicit.
@Stellogic
Copy link
Contributor Author

Stellogic commented Jul 26, 2025

Hi @refraction-ray,
Thank you for the detailed and helpful review! I have updated the code according to your feedback.
Here is a summary of the changes:

Internal API Usage: I've updated the code to use backend from .cons and relative imports for internal modules, instead of calling the top-level tensorcircuit package.

Error Handling: I've added a ValueError check for num_sites = 0 in both Hamiltonian functions, as you suggested.

Rydberg Hamiltonian Sign: Regarding your question on the Z-term sign (why -v_ij/4?), I've double-checked the derivation and I thought the implementation is correct. The single-body Z coefficient comes from two sources:
The detuning term -delta * n_i gives a + (delta / 2) * Z_i contribution.
The interaction term V_ij * n_i * n_j expands to (V_ij / 4) * (1 - Z_i - Z_j + Z_i*Z_j), which contributes - (V_ij / 4) * Z_i to the single-body term.

To make this clearer for future reference, I've also added a comment inside the function explaining this derivation.

I believe this addresses all your feedback. The PR should be ready for another look. Thanks again

import typing
from typing import Any, List, Tuple, Union
import numpy as np
from tensorcircuit.cons import dtypestr, backend
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should also be from ..cons ?

@@ -0,0 +1,154 @@
import typing
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should merge with the following line? import all types you will use

This commit addresses code review feedback on the new hamiltonians module.

- Switched from absolute to relative imports for internal modules (`..cons`, `..quantum`) to improve modularity.
- Cleaned up and unified `typing` imports for better code style and consistency.
@Stellogic
Copy link
Contributor Author

Thanks for the review, @refraction-ray! I've updated the PR according to your suggestions. It should be ready for another look now.

@refraction-ray
Copy link
Member

great! LGTM. will merge if CI finished successfully.

@refraction-ray refraction-ray merged commit 2182cd9 into tensorcircuit:master Jul 26, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants