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

many small fixes, added codestyle tests #96

Merged
merged 6 commits into from
Dec 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 10 additions & 2 deletions .github/workflows/github_actions_automated_testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ jobs:
pip install pytest-cov
pip install jupyter

- name: Install pycodestyle
run: |
python -m pip install pycodestyle

- name: pycodestyle tests
run: |
cd dev_tools
pytest --doctest-modules --junitxml=junit/test-results.xml --cov=com --cov-report=xml --cov-report=html test_conformance.py
if: always()

- name: Install backends except qsharp/qdk
run: |
pip install qiskit
Expand Down Expand Up @@ -60,5 +70,3 @@ jobs:
cd examples
pytest --doctest-modules --junitxml=junit/test-results.xml --cov=com --cov-report=xml --cov-report=html test_notebooks.py
if: always()


6 changes: 6 additions & 0 deletions dev_tools/pycodestyle
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[pycodestyle]
count = False
exclude = *build*
ignore = E123,E126,E127,E128,E201,E202,E226,E241,W503,W504,W605,E741
max-line-length = 160
statistics = True
14 changes: 14 additions & 0 deletions dev_tools/test_conformance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import unittest
import pycodestyle


class TestCodeFormat(unittest.TestCase):

def test_conformance(self):
style = pycodestyle.StyleGuide(quiet=False, config_file="pycodestyle")
result = style.check_files(["../tangelo"])
self.assertEqual(result.total_errors, 0, "Found code style errors and warnings.")


if __name__ == "__main__":
unittest.main()
4 changes: 2 additions & 2 deletions tangelo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
import warnings
import numpy as np

from tangelo.toolboxes.molecular_computation.molecule import Molecule, SecondQuantizedMolecule

sup = np.testing.suppress_warnings()
warnings.filterwarnings("ignore", message="Using default_file_mode other than 'r' is deprecated")
warnings.filterwarnings("ignore", message="`np")
warnings.filterwarnings("ignore", category=DeprecationWarning)
sup.filter(np.core)

from tangelo.toolboxes.molecular_computation.molecule import Molecule, SecondQuantizedMolecule
1 change: 0 additions & 1 deletion tangelo/algorithms/classical/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

1 change: 0 additions & 1 deletion tangelo/algorithms/variational/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

3 changes: 2 additions & 1 deletion tangelo/algorithms/variational/vqe_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ def operator_expectation(self, operator, var_params=None, n_active_mos=None, n_a
if self.molecule:
n_active_mos = self.molecule.n_active_mos
else:
raise KeyError("Must supply n_active_mos when a QubitHamiltonian has initialized VQESolver and requesting the expectation of 'N', 'Sz', or 'S^2'")
raise KeyError("Must supply n_active_mos when a QubitHamiltonian has initialized VQESolver"
" and requesting the expectation of 'N', 'Sz', or 'S^2'")
if operator == "N":
exp_op = number_operator(n_active_mos, up_then_down=False)
elif operator == "Sz":
Expand Down
3 changes: 2 additions & 1 deletion tangelo/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
a default simulator.
"""

import os, sys
import os
import sys


class HiddenPrints:
Expand Down
2 changes: 1 addition & 1 deletion tangelo/linq/qpu_connection/qemist_cloud_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def job_result(qemist_cloud_job_id):
print(f"Reconnect and block until the problem is complete with "
f"qemist_client.util.monitor_problem_status({qemist_cloud_job_id}).\n\n")

except:
except Exception:
print(f"\n\nYour problem is still running with handle {qemist_cloud_job_id}.\n"
f"Cancel the problem with qemist_client.util.cancel_problems({qemist_cloud_job_id}).\n"
f"Reconnect and block until the problem is complete with qemist_client.util.monitor_problem_status({qemist_cloud_job_id}).\n\n")
Expand Down
1 change: 0 additions & 1 deletion tangelo/linq/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

4 changes: 2 additions & 2 deletions tangelo/linq/tests/test_circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ def test_init(self):
def test_is_variational(self):
""" Ensure that the circuit is labeled as variational as soon as one variational gate is present """

self.assertTrue(circuit1.is_variational == False)
self.assertTrue(circuit3.is_variational == True)
self.assertTrue(circuit1.is_variational is False)
self.assertTrue(circuit3.is_variational is True)

def test_width(self):
""" Ensure the width attribute of the circuit object (number of qubits) matches the gate operations
Expand Down
6 changes: 3 additions & 3 deletions tangelo/linq/tests/test_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def test_get_exp_value_from_statevector_h2(self):

try:
self.assertAlmostEqual(energy, expected, delta=1e-5)
except:
except AssertionError:
test_fail = True
print(f"{self._testMethodName} : Assertion failed {b} (result = {energy:.7f}, expected = {expected})")
if test_fail:
Expand Down Expand Up @@ -256,7 +256,7 @@ def test_get_exp_value_from_initial_statevector_h2(self):

try:
self.assertAlmostEqual(energy, expected, delta=1e-5)
except:
except AssertionError:
test_fail = True
print(f"{self._testMethodName} : Assertion failed {b} (result = {energy:.7f}, expected = {expected})")
if test_fail:
Expand Down Expand Up @@ -290,7 +290,7 @@ def test_get_exp_value_from_statevector_h4(self):

try:
self.assertAlmostEqual(energy, expected, delta=1e-5)
except:
except AssertionError:
test_fail = True
print(f"{self._testMethodName} : Assertion failed {b} (result = {energy:.7f}, expected = {expected})")
if test_fail:
Expand Down
2 changes: 1 addition & 1 deletion tangelo/linq/tests/test_simulator_noisy.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def test_get_expectation_value_noisy(self):
noise = 0.00
nmp_no_noise.add_quantum_error("CNOT", "pauli", [noise, noise, noise])
sim_no_noise = Simulator(target=default_simulator, n_shots=10**6, noise_model=nmp_no_noise)

# Small Noise model
nmp_small_noise = NoiseModel()
noise = 0.01
Expand Down
3 changes: 2 additions & 1 deletion tangelo/linq/tests/test_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,8 @@ def test_abs2openqasm(self):
This test failing implies that either Qiskit QASM output has changed or that translate_qiskit fails
(the latter has its own tests)
"""
openqasm_circuit1 = '''OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[3];\ncreg c[3];\nh q[2];\ncx q[0],q[1];\ncx q[1],q[2];\ny q[0];\ns q[0];\nrx(1.5) q[1];\nmeasure q[0] -> c[0];\n'''
openqasm_circuit1 = '''OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[3];\ncreg c[3];\nh q[2];\ncx q[0],q[1];\ncx '''\
'''q[1],q[2];\ny q[0];\ns q[0];\nrx(1.5) q[1];\nmeasure q[0] -> c[0];\n'''
openqasm_circuit2 = translator.translate_openqasm(abs_circ_mixed)
print(openqasm_circuit2)

Expand Down
2 changes: 1 addition & 1 deletion tangelo/molecule_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@

# Beryllium atom.
xyz_Be = [
("Be" , (0., 0., 0.))
("Be", (0., 0., 0.))
]
mol_Be_321g = SecondQuantizedMolecule(xyz_Be, q=0, spin=0, basis="3-21g", frozen_orbitals=None)

Expand Down
1 change: 0 additions & 1 deletion tangelo/problem_decomposition/dmet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

28 changes: 16 additions & 12 deletions tangelo/problem_decomposition/dmet/_helpers/dmet_bath.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import numpy as np


def dmet_fragment_bath(mol, t_list, temp_list, onerdm_low):
""" Construct the bath orbitals for DMET fragment calculation.

Expand Down Expand Up @@ -51,6 +52,7 @@ def dmet_fragment_bath(mol, t_list, temp_list, onerdm_low):

return bath_orb, e_core


def dmet_onerdm_embed(mol, temp_list, onerdm_before):
""" Extract the one particle RDM of the active space.

Expand All @@ -74,19 +76,20 @@ def dmet_onerdm_embed(mol, temp_list, onerdm_before):

if temp_list[0] == 0:
# If it is the first fragment, just determine the maximum for extraction
onerdm_temp = onerdm_matrix[ : , temp_list[1]: ]
onerdm_temp3 = onerdm_temp[temp_list[1]: , : ]
onerdm_temp = onerdm_matrix[:, temp_list[1]:]
onerdm_temp3 = onerdm_temp[temp_list[1]:, :]
else:
# Determine the minimum and maximum orbitals for extraction
onerdm_temp = onerdm_matrix[ : , : temp_list[0]]
onerdm_temp2 = onerdm_matrix[ : , temp_list[1]: ]
onerdm_temp = onerdm_matrix[:, : temp_list[0]]
onerdm_temp2 = onerdm_matrix[:, temp_list[1]:]
onerdm_temp3 = np.hstack((onerdm_temp, onerdm_temp2))
onerdm_temp = onerdm_temp3[ : temp_list[0], : ]
onerdm_temp2 = onerdm_temp3[temp_list[1]: , : ]
onerdm_temp = onerdm_temp3[:temp_list[0], :]
onerdm_temp2 = onerdm_temp3[temp_list[1]:, :]
onerdm_temp3 = np.vstack((onerdm_temp, onerdm_temp2))

return onerdm_temp3


def dmet_bath_orb_sort(t_list, e_before, c_before):
""" Sort the bath orbitals with the eigenvalues (orbital energies).

Expand All @@ -113,11 +116,12 @@ def dmet_bath_orb_sort(t_list, e_before, c_before):

# Sort the bath orbitals with its energies
e_new = e_before[new_index]
c_new = c_before[ : , new_index]
c_new = c_before[:, new_index]

return e_new, c_new

def dmet_add_to_bath_orb( mol, t_list, temp_list, e_before, c_before ):

def dmet_add_to_bath_orb(mol, t_list, temp_list, e_before, c_before):
""" Add the frozen core part to the bath orbitals.

Args:
Expand All @@ -137,12 +141,12 @@ def dmet_add_to_bath_orb( mol, t_list, temp_list, e_before, c_before ):
"""

# Copy the bath orbitals and energies be fore adding the core
add_e = - e_before[t_list[1]: ]
add_c = c_before[ : , t_list[1]: ]
add_e = - e_before[t_list[1]:]
add_c = c_before[:, t_list[1]:]
new_index = add_e.argsort()

# Sort the orbitals based on its energies
c_before[ : , t_list[1]: ] = add_c[ : , new_index]
c_before[:, t_list[1]:] = add_c[:, new_index]
add_e = - add_e[new_index]

# The orbital energies with core part
Expand All @@ -153,7 +157,7 @@ def dmet_add_to_bath_orb( mol, t_list, temp_list, e_before, c_before ):
for orb in range(0, t_list[0]):
c_before = np.insert(c_before, orb, 0.0, axis=1)
i_temp = 0
for orb_total in range( 0, norbital_total ):
for orb_total in range(0, norbital_total):
if ((orb_total >= temp_list[0]) and (orb_total < temp_list[1])):
c_before = np.insert(c_before, orb_total, 0.0, axis=0)
c_before[orb_total, i_temp] = 1.0
Expand Down
15 changes: 8 additions & 7 deletions tangelo/problem_decomposition/dmet/_helpers/dmet_fragment.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
fragment, from the atom list, showing how many atoms included in each fragment.
"""


def dmet_fragment_constructor(mol, atom_list, number_fragment):
"""Construct orbital list.

Expand All @@ -38,19 +39,19 @@ def dmet_fragment_constructor(mol, atom_list, number_fragment):
"""

# Make a new atom list based on how many fragments for DMET calculation
if number_fragment == 0 :
if number_fragment == 0:
atom_list2 = atom_list
else:
# Calculate the number of DMET calculations
number_new_fragment = int(len(atom_list)/(number_fragment+1)) # number of DMET calulation per loop
number_new_fragment = int(len(atom_list)/(number_fragment+1)) # number of DMET calulation per loop
atom_list2 = []

# Define the number of atoms per DMET calculation
for i in range( number_new_fragment ):
for i in range(number_new_fragment):
num = 0
for j in range( number_fragment + 1 ):
for j in range(number_fragment + 1):
k = (number_fragment+1)*i+j
num += atom_list[ k ]
num += atom_list[k]
atom_list2.append(num)

# Initialize the list of the number of orbitals
Expand All @@ -69,11 +70,11 @@ def dmet_fragment_constructor(mol, atom_list, number_fragment):
item = total_basis.split()
item0 = int(item[0])
if (isum <= item0 <= isum2):
itemp+=1
itemp += 1
isum += i
jorb += itemp
orb_list.append(itemp)
orb_list2.append([iorb,jorb])
orb_list2.append([iorb, jorb])
iorb += itemp

return orb_list, orb_list2, atom_list2
6 changes: 4 additions & 2 deletions tangelo/problem_decomposition/dmet/_helpers/dmet_onerdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import numpy as np
from functools import reduce


def dmet_low_rdm(active_fock, number_active_electrons):
"""Construct the one-particle RDM from low-level calculation.

Expand All @@ -37,11 +38,12 @@ def dmet_low_rdm(active_fock, number_active_electrons):
e, c = np.linalg.eigh(active_fock)
new_index = e.argsort()
e = e[new_index]
c = c[ : , new_index]
onerdm = np.dot(c[ : , : int(num_occ)], c[ : , : int(num_occ)].T) * 2
c = c[:, new_index]
onerdm = np.dot(c[:, : int(num_occ)], c[:, : int(num_occ)].T) * 2

return onerdm


def dmet_fragment_rdm(t_list, bath_orb, core_occupied, number_active_electrons):
"""Construct the one-particle RDM for the core orbitals.

Expand Down
11 changes: 6 additions & 5 deletions tangelo/problem_decomposition/dmet/_helpers/dmet_orbitals.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import numpy as np
from functools import reduce


class dmet_orbitals:
""" Localize the SCF orbitals and calculate the integrals

Expand Down Expand Up @@ -81,7 +82,7 @@ def __init__(self, mol, mf, active_space, localization_function):
self.dmet_active_orbitals = np.zeros([mf.mol.nao_nr()], dtype=int)
self.dmet_active_orbitals[active_space] = 1
self.number_active_orbitals = np.sum(self.dmet_active_orbitals)
self.number_active_electrons = int(np.rint(mf.mol.nelectron - np.sum(mf.mo_occ[self.dmet_active_orbitals==0])))
self.number_active_electrons = int(np.rint(mf.mol.nelectron - np.sum(mf.mo_occ[self.dmet_active_orbitals == 0])))

# Localize the orbitals (IAO)
self.localized_mo = localization_function(mol, mf)
Expand Down Expand Up @@ -116,17 +117,17 @@ def dmet_fragment_hamiltonian(self, bath_orb, norb_high, onerdm_core):
"""

# Calculate one-electron integrals
frag_oneint = reduce(np.dot, (bath_orb[ : , : norb_high].T, self.active_oneint, bath_orb[ : , : norb_high]))
frag_oneint = reduce(np.dot, (bath_orb[:, : norb_high].T, self.active_oneint, bath_orb[:, : norb_high]))

# Calculate the fock matrix
density_matrix = reduce(np.dot, (self.localized_mo, onerdm_core, self.localized_mo.T))
two_int = scf.hf.get_veff(self.mol_full, density_matrix, 0, 0, 1)
new_fock = self.active_oneint + reduce(np.dot, ((self.localized_mo.T, two_int, self.localized_mo)))
frag_fock = reduce(np.dot, (bath_orb[ : , : norb_high ].T, new_fock, bath_orb[ : , : norb_high]))
frag_fock = reduce(np.dot, (bath_orb[:, : norb_high].T, new_fock, bath_orb[:, : norb_high]))

# Calculate the two-electron integrals
coefficients = np.dot(self.localized_mo, bath_orb[ : , : norb_high])
frag_twoint = ao2mo.outcore.full_iofree(self.mol_full, coefficients, compact=False).reshape( \
coefficients = np.dot(self.localized_mo, bath_orb[:, : norb_high])
frag_twoint = ao2mo.outcore.full_iofree(self.mol_full, coefficients, compact=False).reshape(
norb_high, norb_high, norb_high, norb_high)

return frag_oneint, frag_fock, frag_twoint
5 changes: 3 additions & 2 deletions tangelo/problem_decomposition/dmet/_helpers/dmet_scf.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from functools import reduce
import numpy as np


def dmet_fragment_scf(t_list, two_ele, fock, number_electrons, number_orbitals, guess_orbitals, chemical_potential):
"""Perform SCF calculation.

Expand Down Expand Up @@ -68,12 +69,12 @@ def dmet_fragment_scf(t_list, two_ele, fock, number_electrons, number_orbitals,
dm_frag = reduce(np.dot, (mf_frag.mo_coeff, np.diag(mf_frag.mo_occ), mf_frag.mo_coeff.T))

# Use newton-raphson algorithm if the above SCF calculation is not converged
if (mf_frag.converged == False):
if (mf_frag.converged is False):
mf_frag.get_hcore = lambda *args: fock_frag_copy
mf_frag.get_ovlp = lambda *args: np.eye(number_orbitals)
mf_frag._eri = ao2mo.restore(8, two_ele, number_orbitals)
mf_frag = scf.RHF(mol_frag).newton()
energy = mf_frag.kernel(dm0 = dm_frag)
energy = mf_frag.kernel(dm0=dm_frag)
dm_frag = reduce(np.dot, (mf_frag.mo_coeff, np.diag(mf_frag.mo_occ), mf_frag.mo_coeff.T))

return mf_frag, fock_frag_copy, mol_frag
Loading