Skip to content

Commit

Permalink
Update dependencies (#243)
Browse files Browse the repository at this point in the history
* Max version for tf probability

* Update workflow to python 3.10

* Bump tf versions

* Checking properties of tf objs compatible with tf 2.15

* Fix for qiskit?

* Remove depricated use of int

* Deprecated use of complex removed

* Update requirements

* Python version as string

* Reblacked, fixed types

* Interface to keras SGD

* try to fix missing qiskit-aer dep

---------

Co-authored-by: lazyoracle <[email protected]>
  • Loading branch information
nwittler and lazyoracle authored Jan 25, 2024
1 parent 57fc8d9 commit 48b7917
Show file tree
Hide file tree
Showing 20 changed files with 40 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build_package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.9]
python-version: ['3.10']
env:
OS: ${{ matrix.os }}
PYTHON: ${{ matrix.python-version }}
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.9]
python-version: ['3.10']
env:
OS: 'ubuntu-latest'
PYTHON: '3.9'
PYTHON: '3.10'
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/format_lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.9]
python-version: ['3.10']
env:
OS: 'ubuntu-latest'
PYTHON: '3.9'
PYTHON: '3.10'
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/nightly_pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ jobs:
- uses: actions/checkout@master
with:
ref: 'dev'
- name: Set up Python 3.9
- name: Set up Python 3.10
uses: actions/setup-python@v1
with:
python-version: 3.9
python-version: 3.10
- name : Install Prerequisites
run : |
sudo apt-add-repository universe
Expand Down Expand Up @@ -49,7 +49,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.9]
python-version: ['3.10']
env:
OS: ${{ matrix.os }}
PYTHON: ${{ matrix.python-version }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/notebook_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
python-version: [3.9]
python-version: ['3.10']
env:
OS: ${{ matrix.os }}
PYTHON: ${{ matrix.python-version }}
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/publish_pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Set up Python 3.9
- name: Set up Python '3.10'
uses: actions/setup-python@v1
with:
python-version: 3.9
python-version: '3.10'
- name : Install Prerequisites
run : |
sudo apt-add-repository universe
Expand Down Expand Up @@ -45,7 +45,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.9]
python-version: ['3.10']
env:
OS: ${{ matrix.os }}
PYTHON: ${{ matrix.python-version }}
Expand Down
11 changes: 4 additions & 7 deletions c3/c3objs.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ def __init__(self, name, desc="", comment="", params=None):
if params:
for pname, par in params.items():
# TODO params here should be the dict representation only
if isinstance(par, Quantity):
self.params[pname] = par
else:
if isinstance(par, dict):
self.params[pname] = Quantity(**par)
else:
self.params[pname] = par

def __str__(self) -> str:
return hjson.dumps(self.asdict(), default=hjson_encode)
Expand Down Expand Up @@ -276,10 +276,7 @@ def _set_value(self, val) -> None:
"""Set the value of this quantity as tensorflow. Value needs to be
within specified min and max."""
# setting can be numpyish
if isinstance(val, ops.EagerTensor) or isinstance(val, ops.Tensor):
val = tf.cast(val, tf.float64)
else:
val = tf.constant(val, tf.float64)
val = tf.constant(val, tf.float64)

tmp = (
2 * (tf.reshape(val, self.shape) * self.pref - self.offset) / self.scale - 1
Expand Down
2 changes: 1 addition & 1 deletion c3/generator/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,7 @@ def __init__(self, **props):

def get_noise(self, sig):
noise_amp = self.params["noise_amp"].get_value().numpy()
bfl_num = np.int(self.params["bfl_num"].get_value().numpy())
bfl_num = int(self.params["bfl_num"].get_value().numpy())
noise = []
bfls = 2 * np.random.randint(2, size=bfl_num) - 1
num_steps = len(sig)
Expand Down
8 changes: 3 additions & 5 deletions c3/libraries/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,9 @@ def tf_fun():

opt_sgd = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=momentum)

for _ in range(iters):
step_count = opt_sgd.minimize(tf_fun, [var])
print(f"epoch {step_count.numpy()}: func_value: {tf_fun()}")
for ii in range(iters):
opt_sgd.minimize(tf_fun, [var])
print(f"iter {ii}: func_value: {tf_fun()}")

result = OptimizeResult(x=var.numpy(), success=True)
return result
Expand Down Expand Up @@ -524,7 +524,6 @@ def cmaes(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
es = cma.CMAEvolutionStrategy(x_init, spread, settings)
iter = 0
while not es.stop():

if shrunk_check:
sigmas.append(es.sigma)
if iter > sigma_conv:
Expand Down Expand Up @@ -627,7 +626,6 @@ def gcmaes(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
es = cma.CMAEvolutionStrategy(x_init, spread, settings)
iter = 0
while not es.stop():

if shrinked_check:
sigmas.append(es.sigma)
if iter > sigma_conv:
Expand Down
2 changes: 0 additions & 2 deletions c3/libraries/propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,6 @@ def tf_expm_dynamic(A, acc=1e-5):
def ode_solver(
model: Model, gen: Generator, instr: Instruction, init_state, solver, step_function
) -> Dict:

signal = gen.generate_signals(instr)

if model.lindbladian:
Expand Down Expand Up @@ -726,7 +725,6 @@ def ode_solver(
def ode_solver_final_state(
model: Model, gen: Generator, instr: Instruction, init_state, solver, step_function
) -> Dict:

signal = gen.generate_signals(instr)

if model.lindbladian:
Expand Down
1 change: 1 addition & 0 deletions c3/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

logging.getLogger("tensorflow").disabled = True


# flake8: noqa: C901
def run_cfg(cfg, opt_config_filename, debug=False):
"""Execute an optimization problem described in the cfg file.
Expand Down
8 changes: 2 additions & 6 deletions c3/optimizers/modellearning.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def __init__(

super().__init__(pmap=pmap, algorithm=algorithm, logger=logger)

self.state_labels = {"all": None}
self.state_labels: Dict[str, List] = {"all": []}
for target, labels in state_labels.items():
self.state_labels[target] = [tuple(lab) for lab in labels]

Expand All @@ -106,7 +106,7 @@ def __init__(
self.inverse = False
self.options = options

self.learn_data = {}
self.learn_data: Dict[str, np.ndarray] = {}
self.read_data(datafiles)
self.sampling = sampling
self.batch_sizes = batch_sizes
Expand Down Expand Up @@ -298,13 +298,11 @@ def goal_run(self, current_params: tf.constant) -> tf.float64:
# TODO: seq per point is not constant. Remove.

for target, data in self.learn_data.items():

self.learn_from = data["seqs_grouped_by_param_set"]
self.gateset_opt_map = data["opt_map"]
indeces = self.select_from_data(self.batch_sizes[target])

for ipar in indeces:

count += 1
data_set = self.learn_from[ipar]
m_vals = data_set["results"][:seqs_pp]
Expand Down Expand Up @@ -376,12 +374,10 @@ def goal_run_with_grad(self, current_params):
count = 0

for target, data in self.learn_data.items():

self.learn_from = data["seqs_grouped_by_param_set"]
self.gateset_opt_map = data["opt_map"]
indeces = self.select_from_data(self.batch_sizes[target])
for ipar in indeces:

count += 1
data_set = self.learn_from[ipar]

Expand Down
1 change: 0 additions & 1 deletion c3/optimizers/sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def __init__(
run_name: str = None,
options={},
) -> None:

super().__init__(
sampling,
batch_sizes,
Expand Down
2 changes: 1 addition & 1 deletion c3/qiskit/c3_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def generate_shot_readout(self):
# TODO a sophisticated readout/measurement routine (w/ SPAM)
return (np.round(self.pops_array * self._shots)).astype("int32").tolist()

def run(self, qobj: qobj.Qobj, **backend_options) -> C3Job:
def run(self, qobj: qobj.QasmQobj, **backend_options) -> C3Job:
"""Parse and run a Qobj
Parameters
Expand Down
1 change: 1 addition & 0 deletions c3/utils/tf_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ def tf_diff(l): # noqa

# MATRIX FUNCTIONS


# TODO - change A.shape[: length-2] to tf.shape
def Id_like(A):
"""Identity of the same size as A."""
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ pytest-cov>=2.11.1
pytest-xdist>=2.2.1
python-dateutil>=2.8.1
qiskit>=0.25.0
qiskit-aer>=0.13.2
rich>=9.2.0
scipy>=1.5.2
six>=1.15.0
Sphinx>=3.2.1
sphinx-autoapi>=1.4.0
tensorflow>=2.4.1,<=2.14.1
tensorflow>=2.15.0
tensorflow-estimator>=2.4.0
tensorflow-probability>=0.12.1
6 changes: 3 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"Operating System :: MacOS",
"Operating System :: Microsoft :: Windows :: Windows 10",
"Operating System :: Unix",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Physics",
],
Expand All @@ -39,9 +39,9 @@
"rich>=9.2.0",
"numpy>=1.23.1",
"scipy>=1.5.2",
"tensorflow>=2.4.1,<=2.14.1",
"tensorflow>=2.15.0",
"tensorflow-estimator>=2.4.0",
"tensorflow-probability>=0.12.1",
],
python_requires="~=3.9",
python_requires="~=3.10",
)
13 changes: 6 additions & 7 deletions test/test_instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,16 +189,13 @@ def test_set_name_ideal():
assert (instr.ideal == GATES["ry90p"]).all()
instr.set_name("crzp")
assert (instr.ideal == GATES["crzp"]).all()
instr.name = 'ry90p'
instr.name = "ry90p"
assert (instr.ideal == GATES["ry90p"]).all()


@pytest.mark.unit
def test_correct_ideal_assignment() -> None:
custom_gate = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]], dtype=np.complex)
custom_gate = np.array([[1.0, 0j, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
propagators = {"custom": custom_gate}
instructions = {"custom": Instruction("custom", ideal=custom_gate)}
psi_0 = np.array([[1], [0], [0], [0]])
Expand All @@ -216,7 +213,7 @@ def test_correct_ideal_assignment() -> None:
@pytest.mark.unit
def test_correct_bloch_rotation_direction():
# makes sure that the rotations on the bloch sphere are in the right direction
GATE_NAME = 'ry90p[0]'
GATE_NAME = "ry90p[0]"
exp = create_experiment()
exp.compute_propagators()
# TODO - remove this line after the ideal updating bug gets fixed...
Expand All @@ -225,4 +222,6 @@ def test_correct_bloch_rotation_direction():
ideal_gate = exp.pmap.instructions[GATE_NAME].get_ideal_gate(dims=[3])
propagator = exp.propagators[GATE_NAME].numpy()
# not equal to one because of imperfections in the propagation
np.testing.assert_array_less(unitary_infid(ideal_gate, propagator, dims=[3]).numpy()[0], 0.05)
np.testing.assert_array_less(
unitary_infid(ideal_gate, propagator, dims=[3]).numpy()[0], 0.05
)
2 changes: 1 addition & 1 deletion test/test_parameter_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def test_parameter_extend() -> None:
Test the setting in optimizer format. Parameter is out of bounds for the
original pmap and should be extended.
"""
pmap.load_values("test/sample_optim_log.c3log",extend_bounds=True)
pmap.load_values("test/sample_optim_log.c3log", extend_bounds=True)
np.testing.assert_almost_equal(
pmap.get_parameter(("rx90p[0]", "d1", "gauss", "freq_offset")).numpy(),
-82997604.24565414,
Expand Down
6 changes: 3 additions & 3 deletions test/test_qt_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_basis(get_test_dimensions) -> None:
"""Testing orthonormality of basis vectors."""
for dim in get_test_dimensions:
pairs = [(i, j) for i in range(dim) for j in range(dim)]
for (i, j) in pairs:
for i, j in pairs:
vi = basis(dim, i)
vj = basis(dim, j)
almost_equal(vi.T @ vj, 1 if i == j else 0)
Expand All @@ -60,7 +60,7 @@ def test_xy_basis(get_test_dimensions) -> None:

# overlap
pairs = [(a, b) for a in names for b in names if b is not a]
for (a, b) in pairs:
for a, b in pairs:
va_p = xy_basis(dim, a + "p")
va_m = xy_basis(dim, a + "m")
vb_p = xy_basis(dim, b + "p")
Expand All @@ -79,7 +79,7 @@ def test_basis_matrices(get_test_dimensions) -> None:

# orthogonality
pairs = [(a, b) for a in matrices for b in matrices if b is not a]
for (a, b) in pairs:
for a, b in pairs:
almost_equal(np.linalg.norm(np.multiply(a, b)), 0)

# normalisation
Expand Down

0 comments on commit 48b7917

Please sign in to comment.