I would like to optimize the purity of input user noisy density matrix using qml.SpecialUnitary after adding ancilla. However, I would like to evaluate purity of the density matrix of the system after tracing out ancilla after evolution of Unitary. Here is my code. My point is shall I have to define a Hamiltonian ? Can It would not be possible after discarding ancilla we evaluate system density matrix then optimize using Gradientdescent. ? I am attching my code

```
## Designing the quantum circuit for purity
import pennylane as qml
from pennylane import numpy as np
import jax
import qutip as qtp
from scipy.optimize import minimize
dev = qml.device('default.mixed', wires = 2)
@qml.qnode(dev)
def circuit(rho,U):
qml.QubitDensityMatrix(rho,wires = [0,1])
# qml.adjoint(qml.QubitUnitary(U,wires = [0,1]))
qml.QubitUnitary(U,wires = [0,1])
return qml.state()
x = 0.412
theta = x * np.array([0, 1, 2, 0, -1, 1, 0, 0, 0, 1, 1, 1, 0, 0, -1])
U = qml.matrix(qml.SpecialUnitary(theta,wires = [0,1]))
rho = sigma
# print("A special unitary rotation gives :")
print(circuit(rho,U).round(2))
@qml.qnode(dev)
def purity(theta):
'''
Initializes a density matrix and takes its purity.
'''
qml.QubitDensityMatrix(circuit(rho,U), wires= [0,1])
return qml.purity(0)
def cost(theta):
'''
Computes linear entropy from purity.
'''
return 1 - purity(theta)
```

In the circuit(), function Is it necessary to define a Hamiltonian like. Here I do not want to measure the system density matrix so I am doing indirect measurement to the ancilla.

```
H = 0.6 * qml.PauliZ(1) - 0.8 * qml.PauliZ(1)
```

Then return its expectation value and optimize?