q-optimize / c3

Toolset for control, calibration and characterization of physical systems
https://c3-toolset.readthedocs.io/
Apache License 2.0
66 stars 36 forks source link

Example for single qubit optimisation with pwc #207

Closed alex-simm closed 2 years ago

alex-simm commented 2 years ago

What

This adds an example file on how to use pwc pulses. For me this currently fails to run.

Why

Seems like pwc is still not working after #202

How

Remarks

Checklist

Please include and complete the following checklist. Your Pull Request is (in most cases) not ready for review until the following have been completed. You can create a draft PR while you are still completing the checklist. Check the Contribution Guidelines for more details. You can mark an item as complete with the - [x] prefix

alex-simm commented 2 years ago
Input In [8], in <cell line: 12>()
      2 opt = OptimalControl(
      3     dir_path=log_dir,
      4     fid_func=fidelities.unitary_infid_set,
   (...)
      9     run_name="X-gate optimisation"
     10 )
     11 opt.set_exp(exp)
---> 12 opt.optimize_controls()
     14 print(opt.current_best_goal)
     15 exp.pmap.print_parameters()

File ~/c3/c3/optimizers/optimalcontrol.py:147, in OptimalControl.optimize_controls(self, setup_log)
    145 x_init = self.pmap.get_parameters_scaled()
    146 try:
--> 147     self.algorithm(
    148         x_init,
    149         fun=self.fct_to_min,
    150         fun_grad=self.fct_to_min_autograd,
    151         grad_lookup=self.lookup_gradient,
    152         options=self.options,
    153     )
    154 except KeyboardInterrupt:
    155     pass

File ~/c3/c3/libraries/algorithms.py:418, in lbfgs(x_init, fun, fun_grad, grad_lookup, options)
    393 """
    394 Wrapper for the scipy.optimize.minimize implementation of LBFG-S. See also:
    395 
   (...)
    414     Scipy result object.
    415 """
    416 # TODO print from the log not from here
    417 # options.update({"disp": True})
--> 418 return minimize(
    419     fun_grad, x_init, jac=grad_lookup, method="L-BFGS-B", options=options
    420 )

File ~/c3/venv/lib64/python3.8/site-packages/scipy/optimize/_minimize.py:681, in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    678     res = _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
    679                              **options)
    680 elif meth == 'l-bfgs-b':
--> 681     res = _minimize_lbfgsb(fun, x0, args, jac, bounds,
    682                            callback=callback, **options)
    683 elif meth == 'tnc':
    684     res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback,
    685                         **options)

File ~/c3/venv/lib64/python3.8/site-packages/scipy/optimize/_lbfgsb_py.py:300, in _minimize_lbfgsb(fun, x0, args, jac, bounds, disp, maxcor, ftol, gtol, eps, maxfun, maxiter, iprint, callback, maxls, finite_diff_rel_step, **unknown_options)
    296     raise ValueError("LBFGSB - one of the lower bounds is greater than an upper bound.")
    298 # initial vector must lie within the bounds. Otherwise ScalarFunction and
    299 # approx_derivative will cause problems
--> 300 x0 = np.clip(x0, new_bounds[0], new_bounds[1])
    302 if disp is not None:
    303     if disp == 0:

File <__array_function__ internals>:180, in clip(*args, **kwargs)

File ~/c3/venv/lib64/python3.8/site-packages/numpy/core/fromnumeric.py:2152, in clip(a, a_min, a_max, out, **kwargs)
   2083 @array_function_dispatch(_clip_dispatcher)
   2084 def clip(a, a_min, a_max, out=None, **kwargs):
   2085     """
   2086     Clip (limit) the values in an array.
   2087 
   (...)
   2150 
   2151     """
-> 2152     return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)

File ~/c3/venv/lib64/python3.8/site-packages/numpy/core/fromnumeric.py:57, in _wrapfunc(obj, method, *args, **kwds)
     54     return _wrapit(obj, method, *args, **kwds)
     56 try:
---> 57     return bound(*args, **kwds)
     58 except TypeError:
     59     # A TypeError occurs if the object does have such a method in its
     60     # class, but its signature is not identical to that of NumPy's. This
   (...)
     64     # Call _wrapit from within the except clause to ensure a potential
     65     # exception has a traceback chain.
     66     return _wrapit(obj, method, *args, **kwds)

File ~/c3/venv/lib64/python3.8/site-packages/numpy/core/_methods.py:159, in _clip(a, min, max, out, casting, **kwargs)
    156     return _clip_dep_invoke_with_casting(
    157         um.maximum, a, min, out=out, casting=casting, **kwargs)
    158 else:
--> 159     return _clip_dep_invoke_with_casting(
    160         um.clip, a, min, max, out=out, casting=casting, **kwargs)

File ~/c3/venv/lib64/python3.8/site-packages/numpy/core/_methods.py:113, in _clip_dep_invoke_with_casting(ufunc, out, casting, *args, **kwargs)
    111 # try to deal with broken casting rules
    112 try:
--> 113     return ufunc(*args, out=out, **kwargs)
    114 except _exceptions._UFuncOutputCastingError as e:
    115     # Numpy 1.17.0, 2019-02-24
    116     warnings.warn(
    117         "Converting the output of clip from {!r} to {!r} is deprecated. "
    118         "Pass `casting=\"unsafe\"` explicitly to silence this warning, or "
   (...)
    121         stacklevel=2
    122     )

File ~/c3/venv/lib64/python3.8/site-packages/tensorflow/python/framework/ops.py:1134, in _EagerTensorBase.__bool__(self)
   1133 def __bool__(self):
-> 1134   return bool(self._numpy())

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
alex-simm commented 2 years ago

Just for completeness: in my code I am using pwc in the same way but the error is different, looks like the same as in #201. Maybe this is related.

File ~/c3/c3/generator/generator.py:209, in Generator.generate_signals(self, instr)
    207 # calculate the output and store it in the stack
    208 dev = self.devices[dev_id]
--> 209 output = dev.process(instr, chan, inputs)
    210 signal_stack[chan][dev_id] = output
    211 #self.global_signal_stack[chan][dev_id] = output
    212 
    213 # remove inputs if they are not needed anymore
   (...)
    218 
    219 # call the callback with the current signal

File ~/c3/c3/generator/devices.py:1187, in AWG.create_IQ(self, instr, chan, inputs)
   1184 ts = self.create_ts(instr.t_start, instr.t_end, centered=True)
   1185 self.ts = ts
-> 1187 signal, norm = instr.get_awg_signal(chan, ts, self.awg_index)
   1189 self.amp_tot = norm
   1190 self.signal[chan] = {
   1191     "inphase": signal["inphase"],
   1192     "quadrature": signal["quadrature"],
   1193     "ts": ts,
   1194 }

File ~/c3/c3/signal/gates.py:330, in Instruction.get_awg_signal(self, chan, ts, awg_index)
    328 freq_offset = comp.params["freq_offset"].get_value()
    329 phase = -xy_angle - freq_offset * ts_off
--> 330 env = comp.get_shape_values(ts_off, t_end - t_start)
    331 env = tf.cast(env, tf.complex128)
    333 signal += (
    334     amp * env * tf.math.exp(tf.complex(tf.zeros_like(phase), phase))
    335 )

File ~/c3/c3/signal/pulse.py:141, in Envelope._get_shape_values_just(self, ts, t_final)
    133 """Return the value of the shape function at the specified times.
    134 
    135 Parameters
   (...)
    138     Vector of time samples.
    139 """
    140 mask = self.compute_mask(ts, t_final)
--> 141 return mask * self.shape(ts, self.params)

File ~/c3/venv/lib64/python3.8/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
    152   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153   raise e.with_traceback(filtered_tb) from None
    154 finally:
    155   del filtered_tb

File ~/c3/venv/lib64/python3.8/site-packages/tensorflow/python/framework/ops.py:7186, in raise_from_not_ok_status(e, name)
   7184 def raise_from_not_ok_status(e, name):
   7185   e.message += (" name: " + name if name is not None else "")
-> 7186   raise core._status_to_exception(e) from None

InvalidArgumentError: Incompatible shapes: [400] vs. [30] [Op:Mul]
codecov[bot] commented 2 years ago

Codecov Report

Merging #207 (a4b7459) into dev (4a8e154) will not change coverage. The diff coverage is n/a.

@@           Coverage Diff           @@
##              dev     #207   +/-   ##
=======================================
  Coverage   74.78%   74.78%           
=======================================
  Files          38       38           
  Lines        5552     5552           
=======================================
  Hits         4152     4152           
  Misses       1400     1400           

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 4a8e154...a4b7459. Read the comment docs.

lazyoracle commented 2 years ago

Does 625b44f5282adf6ea25bac34bb3e3f7d9d4b2409 fix this issue and can we close this PR following the update to the PWC notebook as in 24211ba95b15362124babd82fa1d6af952431b66?

alex-simm commented 2 years ago

Does 625b44f fix this issue and can we close this PR following the update to the PWC notebook as in 24211ba?

Yes it seems to be working now. I'll close this