quaco.js
Version:
A lightweight modular Quantum Computing Simulator in JavaScript. Supports qubits, quantum gates, entanglement, circuits, algorithms, and visualization.
86 lines (75 loc) • 2.59 kB
JavaScript
// src/Circuit.js
import { QuantumRegister } from './QuantumRegister.js';
import { QuantumGate } from './QuantumGate.js';
/**
* Represents a quantum circuit — sequence of gate applications.
*/
export class Circuit {
constructor(numQubits) {
this.numQubits = numQubits;
this.operations = []; // List of { type: 'single'|'cnot', gate, targets }
}
/**
* Add a single-qubit gate operation to the circuit.
* @param {Complex[][]} gateMatrix - 2x2 matrix
* @param {number} targetQubit - index of the qubit
*/
addGate(gateMatrix, targetQubit) {
this.operations.push({
type: 'single',
gate: gateMatrix,
target: targetQubit
});
}
/**
* Add a CNOT gate operation to the circuit.
* @param {number} controlQubit
* @param {number} targetQubit
*/
addCNOT(controlQubit, targetQubit) {
this.operations.push({
type: 'cnot',
control: controlQubit,
target: targetQubit
});
}
/**
* Runs the entire circuit from start on a fresh register.
* @param {number} shots - number of measurement repetitions (default 1)
* @returns {object} histogram of results if shots > 1, else string
*/
run(shots = 1) {
const register = new QuantumRegister(this.numQubits);
const results = {};
for (let shot = 0; shot < shots; shot++) {
// Apply all operations
for (const op of this.operations) {
if (op.type === 'single') {
register.applyGate(op.gate, op.target);
} else if (op.type === 'cnot') {
register.applyCNOT(op.control, op.target);
}
}
const measurement = register.measure();
results[measurement] = (results[measurement] || 0) + 1;
}
if (shots === 1) {
return Object.keys(results)[0];
} else {
return results; // Histogram
}
}
/**
* Prints the circuit operations (for debugging).
*/
printCircuit() {
console.log("Quantum Circuit:");
for (const op of this.operations) {
if (op.type === 'single') {
console.log(`Single-qubit gate on qubit ${op.target}`);
} else if (op.type === 'cnot') {
console.log(`CNOT gate: control ${op.control}, target ${op.target}`);
}
}
}
}