Skip to content
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

Integrate Fermionic QAOA(FQAOA) Module and Associated Files into OpenQAOA #322

Open
wants to merge 26 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f03eaf0
Add __init__.py files
yoshioka1128 Aug 19, 2024
43dbef9
Add fqaoa_workflow.py
yoshioka1128 Aug 23, 2024
6f046f4
Add fqaoa_utils.py
yoshioka1128 Aug 23, 2024
c62d3dc
Add test_fqaoa.py and ensure all tests pass
yoshioka1128 Aug 23, 2024
46af746
Add test_analytical_simulator.py and ensure all tests pass
yoshioka1128 Aug 23, 2024
8eebd64
Add test_workflows.py and ensure all tests pass
yoshioka1128 Aug 23, 2024
fe9eee4
new file: 16_FQAOA_examples.ipynb
yoshioka1128 Aug 23, 2024
ce64508
Add missing imports
yoshioka1128 Aug 23, 2024
31da142
Update documentation for FQAOA
yoshioka1128 Aug 26, 2024
ed49ccb
new file: 17_demonstration_of_quantum_annealing_with_FQAOA.ipynb
yoshioka1128 Aug 27, 2024
d3f08b1
Rename file: 17_demonstration_of_quantum_annealing_with_FQAOA.ipynb
yoshioka1128 Aug 28, 2024
6d2b9b5
Fix typos and minor issues based on review comments
yoshioka1128 Sep 4, 2024
2776652
Fix typos
yoshioka1128 Sep 4, 2024
a7e7c86
Enable prepend_state and update tests
yoshioka1128 Sep 4, 2024
5207488
Reduce complexity and reorganize notebook for better structure
yoshioka1128 Sep 5, 2024
9c607cc
Refine docstrings for improved clarity and accuracy
yoshioka1128 Sep 6, 2024
9a66642
Update notebook for consistency with website presentation
yoshioka1128 Sep 9, 2024
931ad4b
Unified numpy.ndarray references to np.ndarray in docstrings and corr…
yoshioka1128 Sep 24, 2024
2ad8d6b
refactor: remove redundant statevector variable and simplify code. pr…
yoshioka1128 Sep 24, 2024
db9001b
Switched from NumPy to SciPy for determinant calc
yoshioka1128 Sep 25, 2024
5428423
Renumber notebooks and made minor corrections to notebooks.
yoshioka1128 Sep 25, 2024
c19528b
feat: Add type hints and consistency check for statevector sizes
yoshioka1128 Sep 25, 2024
33e7290
deleted: source/notebooks
yoshioka1128 Sep 26, 2024
ac9ac27
Modify objective function to include risk factor
yoshioka1128 Oct 7, 2024
2603d99
Update tests to account for risk factor in objective function
yoshioka1128 Oct 8, 2024
3d6f495
Adjust Jupyter notebook to reflect changes in risk factor implementation
yoshioka1128 Oct 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/openqaoa-core/openqaoa/algorithms/fqaoa/fqaoa_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def get_givens_rotation_angle(orbitals: np.ndarray) -> List[float]:

Parameters
----------
orbitals : numpy.ndarray
orbitals : np.ndarray
A 2D NumPy array representing the matrix of orbitals. The matrix should have a shape of
(n_fermions, n_qubits), where `n_fermions` is the number of rows and `n_qubits` is
the number of columns.
Expand Down Expand Up @@ -79,7 +79,7 @@ def get_statevector(orbitals: np.ndarray) -> np.ndarray:

Returns
-------
numpy.ndarray
np.ndarray
A 1D NumPy array of complex numbers representing the statevector of the quantum system.
The length of this array is `2**n_qubits`, corresponding to all possible basis states.

Expand Down Expand Up @@ -109,7 +109,7 @@ def get_statevector(orbitals: np.ndarray) -> np.ndarray:
for i, j in enumerate(indices):
cof[:, i] = orbitals[:, j]
# Calculate the determinant and store it in the statevector
statevector[inum] = np.linalg.det(cof)
statevector[inum] = linalg.det(cof)

return statevector

Expand Down Expand Up @@ -231,7 +231,7 @@ def get_fermi_orbitals(

Returns
-------
numpy.ndarray
np.ndarray
matrix representation of Fermionic orbitals.

Notes
Expand Down Expand Up @@ -297,7 +297,7 @@ def generate_random_portfolio_data(

# Generate historical-like data for multiple assets over a number of days
random_asset_factors = (1 - 2 * np.random.rand(num_assets)).reshape(-1, 1)
day_indices = np.ndarray([np.arange(num_days) for i in range(num_assets)]) + np.random.randint(10)
day_indices = np.array([np.arange(num_days) for i in range(num_assets)]) + np.random.randint(10)
random_fluctuations = 1 - 2 * np.random.rand(num_assets, num_days)

# The resulting matrix hist_exp represents the daily returns or price levels of the assets
Expand Down Expand Up @@ -377,7 +377,7 @@ def _unitary_sparsification(orbitals: np.ndarray) -> np.ndarray:

Returns
-------
numpy.ndarray
np.ndarray
The modified matrix `orbitals` with its upper triangular elements set to zero.
"""

Expand Down
8 changes: 4 additions & 4 deletions src/openqaoa-core/openqaoa/algorithms/fqaoa/fqaoa_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,11 @@ def set_backend_properties(self, **kwargs):
----------
device: DeviceBase
The device to use for the backend.
prepend_state: Union[openqaoa.basebackend.QuantumCircuitBase,numpy.ndarray(complex)]
prepend_state: Union[openqaoa.basebackend.QuantumCircuitBase,np.ndarray(complex)]
The initial state for FQAOA is specified within the `FQAOA.compile` method, and therefore
`prepend_state` should not be set here. Providing a value for this property will
raise a ValueError.
append_state: Union[QuantumCircuitBase,numpy.ndarray(complex)]
append_state: Union[QuantumCircuitBase,np.ndarray(complex)]
The state appended to the circuit.
init_hadamard: bool
Specifies whether to apply the Hadamard gate during initialization.
Expand All @@ -202,7 +202,7 @@ def set_backend_properties(self, **kwargs):
The value of the CVaR parameter.
noise_model: NoiseModel
The `qiskit` noise model to be used for the shot-based simulator.
initial_qubit_mapping: Union[List[int], numpy.ndarray]
initial_qubit_mapping: Union[List[int], np.ndarray]
Mapping from physical to logical qubit indices, used to eventually
construct the quantum circuit. For example, for a system composed by 3 qubits
`qubit_layout=[1,3,2]`, maps `1<->0`, `3<->1`, `2<->2`, where the left hand side is the physical qubit
Expand Down Expand Up @@ -659,7 +659,7 @@ def _fermi_initial_circuit(self, orbitals: np.ndarray, gate_applicator: object)

Parameters
----------
orbitals : numpy.ndarray
orbitals : np.ndarray
A numpy array containing the orbital information needed to compute the Givens rotation angles.
gate_applicator : object
An object responsible for applying quantum gates to the circuit.
Expand Down
35 changes: 35 additions & 0 deletions src/openqaoa-core/openqaoa/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -1984,3 +1984,38 @@ def to_bin(number, n_qubits):
) / np.sqrt(len(wavefn_locs))

return wavefunction

def is_close_statevector(statevector1, statevector2) -> bool:
yoshioka1128 marked this conversation as resolved.
Show resolved Hide resolved
"""
Checks if statevector1 can be expressed as e^(i*theta) * statevector2.
"""

yoshioka1128 marked this conversation as resolved.
Show resolved Hide resolved
# Threshold for considering a value to be zero
tolerance = 1e-10

# Check if statevector1 is approximately zero where statevector2 is approximately zero
zero_mask_0 = np.isclose(statevector1, 0, atol=tolerance)
zero_mask_1 = np.isclose(statevector2, 0, atol=tolerance)

if np.all(zero_mask_1 == zero_mask_0):
# Create a mask to avoid division by zero
non_zero_mask = ~np.isclose(statevector2, 0, atol=tolerance)

# Compute the ratio with the mask applied
ratio = statevector1[non_zero_mask] / statevector2[non_zero_mask]

# Verify if all ratios have the same phase angle
theta_calculated = np.angle(ratio)
theta_adjusted = (theta_calculated + np.pi) % (2 * np.pi) - np.pi
consistent_phase = np.allclose(theta_adjusted, theta_adjusted[0])

# Verify if all absolute values are same
absolute_ratio = np.abs(statevector1[non_zero_mask] / statevector2[non_zero_mask])
consistent_magnitude = np.allclose(absolute_ratio, absolute_ratio[0])

if consistent_phase and consistent_magnitude:
return True

return False
return False

42 changes: 4 additions & 38 deletions src/openqaoa-core/tests/test_fqaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import copy
import numpy as np

from openqaoa.utilities import is_close_statevector

from openqaoa.algorithms.fqaoa.fqaoa_utils import (
get_analytical_fermi_orbitals,
get_fermi_orbitals,
Expand Down Expand Up @@ -50,8 +52,7 @@ def test_fermi_orbitals_equivalence_to_statevector(self):
]:
analytical_fermi_orbitals = get_analytical_fermi_orbitals(n_qubits, n_fermions, lattice, hopping)
fermi_orbitals = get_fermi_orbitals(n_qubits, n_fermions, lattice, hopping)
statevector = [get_statevector(analytical_fermi_orbitals), get_statevector(fermi_orbitals)]
self.assertTrue(is_close_statevector(statevector[0], statevector[1]),
self.assertTrue(is_close_statevector(get_statevector(analytical_fermi_orbitals), get_statevector(fermi_orbitals)),
"statevector[0] cannot be expressed as e^(i*theta) * statevector[1].")

def test_givens_rotation_angle_length(self):
Expand Down Expand Up @@ -119,8 +120,7 @@ def test_givens_rotation_to_statevector(self):
temp = matrix[ik][icol - 1]
matrix[ik][icol - 1] = temp * np.cos(-angle) - matrix[ik][icol] * np.sin(-angle)
matrix[ik][icol] = temp * np.sin(-angle) + matrix[ik][icol] * np.cos(-angle)
statevector = [get_statevector(orbitals0), get_statevector(matrix)]
self.assertTrue(is_close_statevector(statevector[0], statevector[1]),
self.assertTrue(is_close_statevector(get_statevector(orbitals0), get_statevector(matrix)),
"statevector[0] cannot be expressed as e^(i*theta) * statevector[1].")

# exception handling
Expand Down Expand Up @@ -166,39 +166,5 @@ def is_left_aligned_diagonal_matrix(matrix: np.ndarray) -> bool:
return False
return True

def is_close_statevector(statevector1, statevector2) -> bool:
"""
Checks if statevector1 can be expressed as e^(i*theta) * statevector2.
"""

# Threshold for considering a value to be zero
tolerance = 1e-10

# Check if statevector1 is approximately zero where statevector2 is approximately zero
zero_mask_0 = np.isclose(statevector1, 0, atol=tolerance)
zero_mask_1 = np.isclose(statevector2, 0, atol=tolerance)

if np.all(zero_mask_1 == zero_mask_0):
# Create a mask to avoid division by zero
non_zero_mask = ~np.isclose(statevector2, 0, atol=tolerance)

# Compute the ratio with the mask applied
ratio = statevector1[non_zero_mask] / statevector2[non_zero_mask]

# Verify if all ratios have the same phase angle
theta_calculated = np.angle(ratio)
theta_adjusted = (theta_calculated + np.pi) % (2 * np.pi) - np.pi
consistent_phase = np.allclose(theta_adjusted, theta_adjusted[0])

# Verify if all absolute values are same
absolute_ratio = np.abs(statevector1[non_zero_mask] / statevector2[non_zero_mask])
consistent_magnitude = np.allclose(absolute_ratio, absolute_ratio[0])

if consistent_phase and consistent_magnitude:
return True

return False
return False

if __name__ == '__main__':
unittest.main()
11 changes: 4 additions & 7 deletions src/openqaoa-core/tests/test_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
XY_mixer_hamiltonian,
is_valid_uuid,
ground_state_hamiltonian,
is_close_statevector,
)
from openqaoa.algorithms.workflow_properties import (
BackendProperties,
Expand Down Expand Up @@ -55,8 +56,6 @@
PARAMS_CLASSES_MAPPER,
)

from test_fqaoa import is_close_statevector

def _compare_qaoa_results(dict_old, dict_new):
for key in dict_old.keys():
if key == "cost_hamiltonian": # CHECK WHAT DO WITH THIS
Expand Down Expand Up @@ -2048,9 +2047,7 @@ def test_set_backend_properties_check_backend_vectorized(self):

self.assertEqual(fqaoa.backend.init_hadamard, False)

statevector = [fqaoa.backend.prepend_state, initial_state]
is_close_statevector(statevector[0], statevector[1])
self.assertTrue(is_close_statevector(statevector[0], statevector[1]),
self.assertTrue(is_close_statevector(fqaoa.backend.prepend_state, initial_state),
f"statevector[0] cannot be expressed as e^(i*theta) * statevector[1].")

self.assertEqual(fqaoa.backend.append_state, None)
Expand Down Expand Up @@ -2085,8 +2082,8 @@ def test_set_backend_properties_check_backend_vectorized_w_custom(self):

self.assertEqual(type(fqaoa.backend), QAOAvectorizedBackendSimulator)

statevector = [fqaoa.backend.prepend_state, initial_state]
is_close_statevector(statevector[0], statevector[1])
self.assertTrue(is_close_statevector(fqaoa.backend.prepend_state, initial_state),
f"statevector[0] cannot be expressed as e^(i*theta) * statevector[1].")

self.assertEqual(fqaoa.backend.cvar_alpha, 1)

Expand Down
Loading