Skip to content

Commit

Permalink
fix:memoryleak;minor change
Browse files Browse the repository at this point in the history
  • Loading branch information
lishangshu28 committed Dec 21, 2024
1 parent e1677b7 commit da53daf
Show file tree
Hide file tree
Showing 6 changed files with 16 additions and 11 deletions.
12 changes: 6 additions & 6 deletions quafu/algorithms/gradients/gradiant.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def assemble_grads(para_grads, gate_grads):
return grads


def grad_para_shift(qc: QuantumCircuit, hamiltonian, backend=SVSimulator()):
def grad_para_shift(qc: QuantumCircuit, hamiltonian, backend=SVSimulator(), psi_in = np.array([], dtype=complex)):
"""
Parameter shift gradients. Each gate must have one parameter
"""
Expand All @@ -50,23 +50,23 @@ def grad_para_shift(qc: QuantumCircuit, hamiltonian, backend=SVSimulator()):
" You may need compile the circuit first"
)
op.paras[0] = op.paras[0] + np.pi / 2
res1 = sum(backend.run(qc, hamiltonian=hamiltonian)["pauli_expects"])
res1 = sum(backend.run(qc, hamiltonian=hamiltonian, psi=psi_in)["pauli_expects"])
op.paras[0] = op.paras[0] - np.pi
res2 = sum(backend.run(qc, hamiltonian=hamiltonian)["pauli_expects"])
res2 = sum(backend.run(qc, hamiltonian=hamiltonian, psi=psi_in)["pauli_expects"])
op.paras[0]._undo(2)
gate_grads[i].append((res1 - res2) / 2.0)

return assemble_grads(para_grads, gate_grads)


def grad_finit_diff(qc, hamiltonian, backend=SVSimulator()):
def grad_finit_diff(qc, hamiltonian, backend=SVSimulator(), psi_in = np.array([], dtype=complex)):
variables = qc.variables
grads = []
for v in variables:
v.value += 1e-10
res1 = sum(backend.run(qc, hamiltonian=hamiltonian)["pauli_expects"])
res1 = sum(backend.run(qc, hamiltonian=hamiltonian, psi=psi_in)["pauli_expects"])
v.value -= 2 * 1e-10
res2 = sum(backend.run(qc, hamiltonian=hamiltonian)["pauli_expects"])
res2 = sum(backend.run(qc, hamiltonian=hamiltonian, psi=psi_in)["pauli_expects"])
v.value += 1e-10
grads.append((res1 - res2) / (2 * 1e-10))

Expand Down
3 changes: 1 addition & 2 deletions quafu/circuits/quantum_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,7 @@ def add_ins(self, ins: Instruction):

# pylint: disable=too-many-branches
def add_noise(
self, channel: str, channel_args, qubits: Union[None, List[int]] = None, gates: Union[None, List[str]] = None
,checkgates=True):
self, channel: str, channel_args, qubits: Union[None, List[int]] = None, gates: Union[None, List[str]] = None, checkgates=True):
if qubits is None:
qubits = []
if gates is None:
Expand Down
4 changes: 2 additions & 2 deletions quafu/results/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def probabilities(self):
def counts(self):
return self["counts"]

def calc_probabilities(self, from_counts=True):
def calc_probabilities(self, from_counts=False):
num = self["qbitnum"]
if from_counts and self._meta_data['counts']:
counts = self._meta_data["counts"]
Expand All @@ -161,7 +161,7 @@ def calc_probabilities(self, from_counts=True):
values = np.argsort(values_tmp)

# pylint: disable=import-outside-toplevel
from quafu.simulators.default_simulator import permutebits, ptrace
from quafu.simulators.default_simulator import permutebits, ptrace

psi = permutebits(psi, range(num)[::-1])
if measures:
Expand Down
2 changes: 1 addition & 1 deletion quafu/simulators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def simulate(
qc: Union[QuantumCircuit, str],
psi: np.ndarray = np.array([]),
simulator: str = "statevector",
shots: int = 100,
shots: int = 0,
hamiltonian=None,
use_gpu: bool = False,
use_custatevec: bool = False,
Expand Down
2 changes: 2 additions & 0 deletions src/qfvm/instructions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class Instruction {
Instruction(){};
Instruction(string const& name, vector<pos_t> const& positions) : name_(name), positions_(positions) {
}
virtual ~Instruction() = default;
string name() const {
return name_;
}
Expand All @@ -38,6 +39,7 @@ class Instruction {
return !(name_ == "empty");
}


// interface
virtual vector<double> paras() const {
return {};
Expand Down
4 changes: 4 additions & 0 deletions tests/quafu/simulator/basis_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ def test_measure_atlast_collapse(self):
self.circuit = BellCircuits.bell_measure_atlast()
result = simulate(qc=self.circuit)
probs = result.probabilities
# print(probs)
self.assertAlmostEqual(probs[0], 1 / 2)
self.assertAlmostEqual(probs[1], 0)
self.assertAlmostEqual(probs[2], 0)
Expand Down Expand Up @@ -314,3 +315,6 @@ def test_anycbit_measure(self):
result = simulate(qc=self.circuit, shots=10, simulator="clifford")
counts = result.counts
self.assert_dict_almost_equal(counts, {"0101": 10})

if __name__ == "__main__":
TestSimulatorBasis().test_measure_atlast_collapse()

0 comments on commit da53daf

Please sign in to comment.