From 5d74c5e01d8032bc499f96f0019e55f03401df9d Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Sat, 1 Jun 2019 15:08:17 +0200 Subject: [PATCH] allow custom gates to be overwritten This commit adds the ability to overwrite/redefine the a custom gate. The motivation for this came from wanting to have multiple circuits in a program and allow them to have the same name for a custom gate, but the matrix for the gate would be different for each circuit. --- CHANGELOG.md | 1 + packages/qiskit-sim/lib/gates.js | 4 +++- packages/qiskit-sim/test/functional/gates.js | 10 ++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d47496..149086b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - `@qiskit/qiskit-sim`: add prettyMatrix method to Gate class - `@qiskit/qiskit-sim`: add gates to gates map in constructor - `@qiskit/qiskit-sim`: remove unused addGate function in grammar.jison +- `@qiskit/qiskit-sim`: allow custom gates to be overwritten ## [0.9.0] - 2019-05-13 diff --git a/packages/qiskit-sim/lib/gates.js b/packages/qiskit-sim/lib/gates.js index 76fd859..dae0fca 100644 --- a/packages/qiskit-sim/lib/gates.js +++ b/packages/qiskit-sim/lib/gates.js @@ -43,12 +43,13 @@ const phaseShift = shift => [[1, 0], [0, math.pow(math.e, math.multiply(math.i, math.PI / shift))]]; const gates = new Map(); +let builtinGateNames; class Gate { constructor(name, matrix) { this.name = name; this.matrix = matrix; - if (!gates.has(name)) { + if (!builtinGateNames || !builtinGateNames.has(name)) { gates.set(name, this); } } @@ -103,6 +104,7 @@ Gate.cs = new Gate('cs', buildControlled(Gate.s)); Gate.cr2 = new Gate('cr2', buildControlled(Gate.r2)); Gate.cr4 = new Gate('cr4', buildControlled(Gate.r4)); Gate.cr8 = new Gate('cr8', buildControlled(Gate.r8)); +builtinGateNames = new Set(gates.keys()); module.exports = { Gate, diff --git a/packages/qiskit-sim/test/functional/gates.js b/packages/qiskit-sim/test/functional/gates.js index 5d85a5f..5697d6d 100644 --- a/packages/qiskit-sim/test/functional/gates.js +++ b/packages/qiskit-sim/test/functional/gates.js @@ -55,4 +55,14 @@ describe('sim:gates', () => { const custom = new Gate('custom', [[1, 0], [0, 1]]); assert.ok(gates.has(custom.name)); }); + + it('custom gate should be allowed to be overwritten', () => { + const custom = new Gate('custom', [[1, 0], [0, 1]]); + const newMatrix = [[1, 0], + [1, 1]]; + const overwrite = new Gate(custom.name, newMatrix); + assert.ok(gates.has(overwrite.name)); + assert.strictEqual(gates.get(custom.name).matrix, newMatrix); + }); + });