qml.pulse.rect

rect(x, windows=None)[source]

Takes a scalar or a scalar-valued function, x, and applies a rectangular window to it, such that the returned function is x inside the window and 0 outside it.

Creates a callable for defining a ParametrizedHamiltonian.

Parameters
  • x (Union[float, Callable]) – either a scalar, or a function that accepts two arguments: the trainable parameters and time

  • windows (Union[Tuple[float], List[Tuple[float]]]) – List of tuples containing time windows where x is evaluated. If None it is always evaluated. Defaults to None.

Returns

A callable f(p, t) which evaluates the given function/scalar x inside the time windows defined in windows, and otherwise returns 0.

Return type

callable

Note

If x is a function, it must accept two arguments: the trainable parameters and time. The primary use of rect is for numerical simulations via ParametrizedEvolution, which assumes t to be a single scalar argument. If you need to efficiently compute multiple times, you need to broadcast over t via jax.vmap (see examples below).

Example

Here we use rect() to create a parametrized coefficient that has a value of 0 outside the time interval t=(1, 7), and is defined by jnp.polyval(p, t) within the interval:

def f(p, t):
    return jnp.polyval(p, t)

p = jnp.array([1, 2, 3])
time = jnp.linspace(0, 10, 1000)
windows = [(1, 7)]

windowed_f = qml.pulse.rect(f, windows=windows)

y1 = f(p, time)
y2 = jax.vmap(windowed_f, (None, 0))(p, time)

plt.plot(time, y1, label=f"polyval(p={p}, t)")
plt.plot(time, y2, label=f"rect(polyval, windows={windows})(p={p}, t)")
plt.legend()
plt.xlabel("t")
plt.show()
../../_images/rect_example.png

Note that in order to efficiently create y2, we broadcasted windowed_f over the time argument using jax.vmap.

rect can be used to create a ParametrizedHamiltonian in the following way:

>>> H = qml.pulse.rect(jnp.polyval, windows=[(1, 7)]) * qml.X(0)

The resulting Hamiltonian will be non-zero only inside the window.

>>> H([[1, 3]], t=2)  # inside the window
5.0 * X(0)
>>> H([[1, 3]], t=0.5 )  # outside the window
0.0 * X(0)

It is also possible to define multiple windows for the same function:

windows = [(1, 7), (9, 14)]
H = qml.pulse.rect(jnp.polyval, windows) * qml.X(0)

When calling the ParametrizedHamiltonian, rect will evaluate the given function only inside the time windows, and otherwise return 0.

One can also pass a scalar to the rect function

>>> H = qml.pulse.rect(10, (1, 7)) * qml.X(0)

In this case, rect will return the given scalar only when the time is inside the provided time windows

>>> params = [None]  # the parameter value won't be used!
>>> H(params, t=8)
0.0 * X(0)
>>> H(params, t=5)
10.0 * X(0)