code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
cycleBitsShader = (ctx, qubitSpan, shiftAmount) =>
CYCLE_SHADER.withArgs(
...ketArgs(ctx, qubitSpan),
WglArg.float("amount", 1 << Util.properMod(-shiftAmount, qubitSpan))) | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan
@param {!int} shiftAmount
@returns {!WglConfiguredShader} | cycleBitsShader | javascript | Strilanc/Quirk | src/gates/CycleBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/CycleBitsGates.js | Apache-2.0 |
makeCycleBitsPermutation = (shift, span) => e => {
shift = Util.properMod(shift, span);
return ((e << shift) & ((1 << span) - 1)) | (e >> (span - shift));
} | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan
@param {!int} shiftAmount
@returns {!WglConfiguredShader} | makeCycleBitsPermutation | javascript | Strilanc/Quirk | src/gates/CycleBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/CycleBitsGates.js | Apache-2.0 |
makeCycleBitsPermutation = (shift, span) => e => {
shift = Util.properMod(shift, span);
return ((e << shift) & ((1 << span) - 1)) | (e >> (span - shift));
} | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan
@param {!int} shiftAmount
@returns {!WglConfiguredShader} | makeCycleBitsPermutation | javascript | Strilanc/Quirk | src/gates/CycleBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/CycleBitsGates.js | Apache-2.0 |
cyclePainter = reverse => args => {
if (args.positionInCircuit !== undefined) {
GatePainting.PERMUTATION_DRAWER(args);
return;
}
GatePainting.paintBackground(args);
GatePainting.paintOutline(args);
GatePainting.paintResizeTab(args);
let x1 = args.rect.x + 6;
let x2 = args.r... | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan
@param {!int} shiftAmount
@returns {!WglConfiguredShader} | cyclePainter | javascript | Strilanc/Quirk | src/gates/CycleBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/CycleBitsGates.js | Apache-2.0 |
cyclePainter = reverse => args => {
if (args.positionInCircuit !== undefined) {
GatePainting.PERMUTATION_DRAWER(args);
return;
}
GatePainting.paintBackground(args);
GatePainting.paintOutline(args);
GatePainting.paintResizeTab(args);
let x1 = args.rect.x + 6;
let x2 = args.r... | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan
@param {!int} shiftAmount
@returns {!WglConfiguredShader} | cyclePainter | javascript | Strilanc/Quirk | src/gates/CycleBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/CycleBitsGates.js | Apache-2.0 |
function densityDisplayStatTexture(inp, qubitCount, controls, rangeOffset, rangeLength) {
let trader = new WglTextureTrader(inp);
trader.dontDeallocCurrentTexture();
// Put into normal form by throwing away areas not satisfying the controls and cycling the offset away.
let startingQubits = currentShade... | @param {!WglTexture} inp
@param {!Controls} controls
@param {!int} qubitCount
@param {!int} rangeOffset
@param {!int} rangeLength
@returns {!WglTexture} | densityDisplayStatTexture | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
amplitudesToCouplings = (inputTexture, qubitSpan) => AMPLITUDES_TO_DENSITIES_SHADER(
inputTexture,
WglArg.float('qubitSpan', 1 << qubitSpan)) | @param {!WglTexture} inputTexture
@param {!int} qubitSpan
@returns {!WglConfiguredShader} | amplitudesToCouplings | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
amplitudesToCouplings = (inputTexture, qubitSpan) => AMPLITUDES_TO_DENSITIES_SHADER(
inputTexture,
WglArg.float('qubitSpan', 1 << qubitSpan)) | @param {!WglTexture} inputTexture
@param {!int} qubitSpan
@returns {!WglConfiguredShader} | amplitudesToCouplings | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
function decohereMeasuredBitsInDensityMatrix(densityMatrix, isMeasuredMask) {
if (isMeasuredMask === 0) {
return densityMatrix;
}
let buf = new Float32Array(densityMatrix.rawBuffer());
let n = densityMatrix.width();
for (let row = 0; row < n; row++) {
for (let col = 0; col < n; col+... | Returns the same density matrix, but without any diagonal terms related to qubits that have been measured.
@param {!Matrix} densityMatrix
@param {!int} isMeasuredMask A bitmask where each 1 corresponds to a measured qubit position.
@returns {!Matrix} | decohereMeasuredBitsInDensityMatrix | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
function densityPixelsToMatrix(pixels, circuitDefinition, col, row) {
let n = pixels.length >> 1;
let d = Math.round(Math.sqrt(n));
let unity = 0;
for (let i = 0; i < d; i++) {
unity += pixels[2*i*(d+1)];
}
if (isNaN(unity) || unity < 0.000001) {
return Matrix.zero(d, d).times(Na... | Post-processes the pixels that come out of makeDensityPipeline into a vector of normalized probabilities.
@param {!Float32Array} pixels
@param {!CircuitDefinition} circuitDefinition
@param {!int} col
@param {!int} row
@returns {!Matrix} | densityPixelsToMatrix | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
function largeDensityMatrixDisplayMaker(span, builder) {
return densityMatrixDisplayMaker_shared(builder).
setSerializedId("Density" + span).
setWidth(span).
setDrawer(DENSITY_MATRIX_DRAWER_FROM_CUSTOM_STATS).
setProcessedStatsToJsonFunc(data => {
return {density_matrix: ... | @param {!int} span
@param {!GateBuilder} builder
@returns {!GateBuilder} | largeDensityMatrixDisplayMaker | javascript | Strilanc/Quirk | src/gates/DensityMatrixDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/DensityMatrixDisplay.js | Apache-2.0 |
function controlMaskTex(ctx, controls) {
let powerSize = currentShaderCoder().vec2.arrayPowerSizeOfTexture(ctx.stateTrader.currentTexture);
return CircuitShaders.controlMask(controls).toBoolTexture(powerSize);
} | @param {!CircuitEvalContext} ctx
@param {!Controls} controls
@returns {!WglTexture} | controlMaskTex | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function textureWithTotalWeightMatchingGivenControls(ketTexture, controlMaskTex, forStats=false) {
let powerSize = currentShaderCoder().vec2.arrayPowerSizeOfTexture(ketTexture);
// Convert the matching amplitudes to probabilities (and the non-matching ones to 0).
let trader = new WglTextureTrader(ketTextur... | Prepares a 1x1 texture containing the total squared-magnitude of states matching the given controls.
@param {!WglTexture} ketTexture
@param {!WglTexture} controlMaskTex
@param {!boolean} forStats
@returns {!WglTexture} | textureWithTotalWeightMatchingGivenControls | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function switchToBasis(ctx, axis, inverse) {
switch (axis) {
case 'X':
GateShaders.applyMatrixOperation(ctx, HalfTurnGates.H.knownMatrixAt(0));
break;
case 'Y':
if (inverse) {
GateShaders.applyMatrixOperation(ctx, QuarterTurnGates.SqrtXBackward.kno... | @param {!CircuitEvalContext} ctx
@param {!string} axis
@param {!boolean} inverse | switchToBasis | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function sampleMeasure(ctx) {
let maskAll = controlMaskTex(ctx, Controls.NONE);
let maskMatch = controlMaskTex(ctx, ctx.controls.and(Controls.bit(ctx.row, true)));
let weightAll = textureWithTotalWeightMatchingGivenControls(ctx.stateTrader.currentTexture, maskAll);
let weightMatch = textureWithTotalWeig... | Applies a sample measurement operation to the state.
@param {!CircuitEvalContext} ctx | sampleMeasure | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function drawDetector(args, axis) {
drawHighlight(args);
drawWedge(args, axis);
drawClick(args, axis);
} | @param {!GateDrawParams} args
@param {!string} axis | drawDetector | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function drawClick(args, axis) {
// Draw tilted "*click*" text.
let clicked = args.customStats;
if (!clicked) {
return;
}
let r = Math.min(args.rect.h / 2, args.rect.w);
args.painter.ctx.save();
args.painter.ctx.translate(args.rect.center().x, args.rect.center().y);
args.painter.ctx.... | @param {!GateDrawParams} args
@param {undefined|!string} axis | drawClick | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function drawControlBulb(args, axis) {
redrawControlWires(args);
let p = args.rect.center();
switch (axis) {
case 'X':
args.painter.fillCircle(p, 5);
args.painter.strokeCircle(p, 5);
args.painter.strokeLine(p.offsetBy(0, -5), p.offsetBy(0, +5));
args.p... | @param {!GateDrawParams} args
@param {!string} axis | drawControlBulb | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function withClearedControls(func) {
return ctx => {
let controls = ctx.controls;
let texture = ctx.controlsTexture;
try {
ctx.controls = Controls.NONE;
ctx.controlsTexture = controlMaskTex(ctx, ctx.controls);
return func(ctx);
} finally {
... | @param {!function(!CircuitEvalContext) : T} func
@returns {!function(!CircuitEvalContext) : T}
@template T | withClearedControls | javascript | Strilanc/Quirk | src/gates/Detector.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/Detector.js | Apache-2.0 |
function applyControlledPhaseGradient(ctx, qubitSpan, factor=1) {
ctx.applyOperation(CONTROLLED_PHASE_GRADIENT_SHADER.withArgs(
...ketArgs(ctx, qubitSpan),
WglArg.float("factor", factor)));
} | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan Size of the gate.
@param {!number=} factor Scaling factor for the applied phases. | applyControlledPhaseGradient | javascript | Strilanc/Quirk | src/gates/FourierTransformGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/FourierTransformGates.js | Apache-2.0 |
FOURIER_TRANSFORM_MATRIX_MAKER = span =>
Matrix.generate(1<<span, 1<<span, (r, c) => Complex.polar(Math.pow(0.5, span/2), Math.PI*2*r*c/(1<<span))) | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan Size of the gate.
@param {!number=} factor Scaling factor for the applied phases. | FOURIER_TRANSFORM_MATRIX_MAKER | javascript | Strilanc/Quirk | src/gates/FourierTransformGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/FourierTransformGates.js | Apache-2.0 |
FOURIER_TRANSFORM_MATRIX_MAKER = span =>
Matrix.generate(1<<span, 1<<span, (r, c) => Complex.polar(Math.pow(0.5, span/2), Math.PI*2*r*c/(1<<span))) | @param {!CircuitEvalContext} ctx
@param {!int} qubitSpan Size of the gate.
@param {!number=} factor Scaling factor for the applied phases. | FOURIER_TRANSFORM_MATRIX_MAKER | javascript | Strilanc/Quirk | src/gates/FourierTransformGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/FourierTransformGates.js | Apache-2.0 |
function applyForwardGradientShaders(ctx, span) {
if (span > 1) {
ctx.applyOperation(reverseShaderForSize(span));
}
for (let i = 0; i < span; i++) {
if (i > 0) {
applyControlledPhaseGradient(ctx, i + 1, +1);
}
HalfTurnGates.H.customOperation(ctx.withRow(ctx.row + ... | @param {!CircuitEvalContext} ctx
@param {!int} span | applyForwardGradientShaders | javascript | Strilanc/Quirk | src/gates/FourierTransformGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/FourierTransformGates.js | Apache-2.0 |
function applyBackwardGradientShaders(ctx, span) {
for (let i = span - 1; i >= 0; i--) {
HalfTurnGates.H.customOperation(ctx.withRow(ctx.row + i));
if (i > 0) {
applyControlledPhaseGradient(ctx, i + 1, -1);
}
}
if (span > 1) {
ctx.applyOperation(reverseShaderForSi... | @param {!CircuitEvalContext} ctx
@param {!int} span | applyBackwardGradientShaders | javascript | Strilanc/Quirk | src/gates/FourierTransformGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/FourierTransformGates.js | Apache-2.0 |
function NOT_DRAWER(args) {
if (args.isHighlighted) {
GatePainting.DEFAULT_DRAWER(args);
return;
}
// Show a box around the operation when it's not in the circuit.
if (args.positionInCircuit === undefined) {
GatePainting.paintBackground(args);
GatePainting.paintOutline(a... | The X gate is drawn as a crossed circle when it has controls.
@param {!GateDrawParams} args | NOT_DRAWER | javascript | Strilanc/Quirk | src/gates/HalfTurnGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/HalfTurnGates.js | Apache-2.0 |
function drawInputGate(args, key, reverse) {
GatePainting.paintBackground(args, '#DDD', '#DDD');
if (args.isInToolbox) {
GatePainting.paintOutline(args);
} else {
args.painter.strokeRect(args.rect, '#888');
}
GatePainting.paintResizeTab(args);
let {x, y} = args.rect.center();
... | @param {!GateDrawParams} args
@param {!string} key
@param {!boolean} reverse | drawInputGate | javascript | Strilanc/Quirk | src/gates/InputGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InputGates.js | Apache-2.0 |
makeInputGate = (key, reverse) => Gate.buildFamily(1, 16, (span, builder) => builder.
setSerializedId((reverse ? 'rev' : '') + `input${key}${span}`).
setSymbol((reverse ? 'rev ' : '') + `input ${key}`).
setTitle(`Input Gate [${key}]` + (reverse ? ' [reversed]' : '')).
setBlurb(`Temporarily uses some qub... | @param {!GateDrawParams} args
@param {!string} key
@param {!boolean} reverse | makeInputGate | javascript | Strilanc/Quirk | src/gates/InputGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InputGates.js | Apache-2.0 |
makeInputGate = (key, reverse) => Gate.buildFamily(1, 16, (span, builder) => builder.
setSerializedId((reverse ? 'rev' : '') + `input${key}${span}`).
setSymbol((reverse ? 'rev ' : '') + `input ${key}`).
setTitle(`Input Gate [${key}]` + (reverse ? ' [reversed]' : '')).
setBlurb(`Temporarily uses some qub... | @param {!GateDrawParams} args
@param {!string} key
@param {!boolean} reverse | makeInputGate | javascript | Strilanc/Quirk | src/gates/InputGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InputGates.js | Apache-2.0 |
makeSetInputGate = key => new GateBuilder().
setSerializedIdAndSymbol(`set${key}`).
setTitle(`Set Default ${key}`).
setBlurb(`Sets a default value for input ${key}, for when an inline input isn't given.`).
setWidth(2).
setHeight(2).
promiseHasNoNetEffectOnStateVector().
markAsNotInterestedIn... | @param {!GateDrawParams} args
@param {!string} key
@param {!boolean} reverse | makeSetInputGate | javascript | Strilanc/Quirk | src/gates/InputGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InputGates.js | Apache-2.0 |
makeSetInputGate = key => new GateBuilder().
setSerializedIdAndSymbol(`set${key}`).
setTitle(`Set Default ${key}`).
setBlurb(`Sets a default value for input ${key}, for when an inline input isn't given.`).
setWidth(2).
setHeight(2).
promiseHasNoNetEffectOnStateVector().
markAsNotInterestedIn... | @param {!GateDrawParams} args
@param {!string} key
@param {!boolean} reverse | makeSetInputGate | javascript | Strilanc/Quirk | src/gates/InputGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InputGates.js | Apache-2.0 |
function interleaveBit(bit, len) {
let h = Math.ceil(len / 2);
let group = Math.floor(bit / h);
let stride = bit % h;
return stride * 2 + group;
} | Transforms from a block bit position to a striped bit position.
@param {!int} bit
@param {!int} len
@returns {!int} | interleaveBit | javascript | Strilanc/Quirk | src/gates/InterleaveBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InterleaveBitsGates.js | Apache-2.0 |
function deinterleaveBit(bit, len) {
let h = Math.ceil(len / 2);
let stride = Math.floor(bit / 2);
let group = bit % 2;
return stride + group * h;
} | Transforms from a striped bit position to a block bit position.
@param {!int} bit
@param {!int} len
@returns {!int} | deinterleaveBit | javascript | Strilanc/Quirk | src/gates/InterleaveBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InterleaveBitsGates.js | Apache-2.0 |
function shaderFromBitPermutation(span, bitPermutation) {
let bitMoveLines = [];
for (let i = 0; i < span; i++) {
bitMoveLines.push(`r += mod(floor(out_id / ${1 << bitPermutation(i, span)}.0), 2.0) * ${1 << i}.0;`);
}
return ketShaderPermute(
'',
`
float r = 0.0;
... | Constructs a shader that permutes bits based on the given function.
@param {!int} span
@param {!function(bit: !int, len: !int) : !int} bitPermutation
@return {!{withArgs: !function(args: ...!WglArg|!WglTexture) : !WglConfiguredShader}} | shaderFromBitPermutation | javascript | Strilanc/Quirk | src/gates/InterleaveBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InterleaveBitsGates.js | Apache-2.0 |
interleavePainter = reverse => args => {
if (args.positionInCircuit !== undefined) {
GatePainting.PERMUTATION_DRAWER(args);
return;
}
GatePainting.paintBackground(args);
GatePainting.paintOutline(args);
GatePainting.paintResizeTab(args);
let x1 = args.rect.x + 6;
let x2 = a... | @type {!Map.<!int, !{withArgs: !function(args: ...!WglArg|!WglTexture) : !WglConfiguredShader}>} | interleavePainter | javascript | Strilanc/Quirk | src/gates/InterleaveBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InterleaveBitsGates.js | Apache-2.0 |
interleavePainter = reverse => args => {
if (args.positionInCircuit !== undefined) {
GatePainting.PERMUTATION_DRAWER(args);
return;
}
GatePainting.paintBackground(args);
GatePainting.paintOutline(args);
GatePainting.paintResizeTab(args);
let x1 = args.rect.x + 6;
let x2 = a... | @type {!Map.<!int, !{withArgs: !function(args: ...!WglArg|!WglTexture) : !WglConfiguredShader}>} | interleavePainter | javascript | Strilanc/Quirk | src/gates/InterleaveBitsGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/InterleaveBitsGates.js | Apache-2.0 |
modulusTooBigChecker = (inputKey, span, modName='mod') => args => {
let r = args.context.get('Input Range ' + inputKey);
let d = args.context.get('Input Default ' + inputKey);
if (r !== undefined && r.length > span) {
return `${modName}\ntoo\nbig`;
}
if (r === undefined && d !== undefined &&... | @param {!string} inputKey
@param {!int} span
@param {!string=} modName
@returns {!function(!GateCheckArgs) : (undefined|!string)} | modulusTooBigChecker | javascript | Strilanc/Quirk | src/gates/ModularIncrementGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ModularIncrementGates.js | Apache-2.0 |
modulusTooBigChecker = (inputKey, span, modName='mod') => args => {
let r = args.context.get('Input Range ' + inputKey);
let d = args.context.get('Input Default ' + inputKey);
if (r !== undefined && r.length > span) {
return `${modName}\ntoo\nbig`;
}
if (r === undefined && d !== undefined &&... | @param {!string} inputKey
@param {!int} span
@param {!string=} modName
@returns {!function(!GateCheckArgs) : (undefined|!string)} | modulusTooBigChecker | javascript | Strilanc/Quirk | src/gates/ModularIncrementGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ModularIncrementGates.js | Apache-2.0 |
function modularMultiply(val, factor, modulus) {
if (val >= modulus) {
return val;
}
factor = Util.properMod(factor, modulus);
if (factor === 0 || Util.extended_gcd(factor, modulus).gcd !== 1) {
return val;
}
return (val * factor) % modulus;
} | Multiplies the value by the given factor, modulo the given modulus, but with tweaks to avoid irreversible actions.
If the value is out of range or the factor is not invertible, nothing happens.
@param {!int} val
@param {!int} factor
@param {!int} modulus
@returns {!int} | modularMultiply | javascript | Strilanc/Quirk | src/gates/ModularMultiplicationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ModularMultiplicationGates.js | Apache-2.0 |
function modularUnmultiply(val, factor, modulus) {
if (val >= modulus) {
return val;
}
factor = Util.properMod(factor, modulus);
if (factor === 0) {
return val;
}
let inverse_factor = Util.modular_multiplicative_inverse(factor, modulus);
if (inverse_factor === undefined) {
... | Un-multiplies the value by the given factor, modulo the given modulus, but with tweaks to avoid irreversible actions.
If the value is out of range or the factor is not invertible, nothing happens.
@param {!int} val
@param {!int} factor
@param {!int} modulus
@returns {!int} | modularUnmultiply | javascript | Strilanc/Quirk | src/gates/ModularMultiplicationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ModularMultiplicationGates.js | Apache-2.0 |
function modularPowerMultiply(val, base, exponent, modulus) {
if (val >= modulus) {
return val;
}
base = Util.properMod(base, modulus);
let inverse = Util.modular_multiplicative_inverse(base, modulus);
if (inverse === undefined) {
return val;
}
if (exponent < 0) {
ex... | @param {!int} val
@param {!int} base
@param {!int} exponent
@param {!int} modulus
@returns {!int} | modularPowerMultiply | javascript | Strilanc/Quirk | src/gates/ModularMultiplicationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ModularMultiplicationGates.js | Apache-2.0 |
function configurableRotationDrawer(pattern, xyz, tScale) {
let xScale = [1, 0.5, -1][xyz];
let yScale = [1, 1, -0.5][xyz];
return args => {
GatePainting.paintBackground(args, Config.TIME_DEPENDENT_HIGHLIGHT_COLOR);
GatePainting.paintOutline(args);
let text = pattern;
if (!ar... | @param {!string} pattern
@param {!int} xyz
@param {!number} tScale
@returns {!function(args: !GateDrawParams)} | configurableRotationDrawer | javascript | Strilanc/Quirk | src/gates/ParametrizedRotationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ParametrizedRotationGates.js | Apache-2.0 |
function parseTimeFormula(formula, time, warn) {
let tokenMap = new Map([...PARSE_COMPLEX_TOKEN_MAP_RAD.entries()]);
if (time !== undefined) {
tokenMap.set('t', time);
}
try {
let angle = Complex.from(parseFormula(formula, tokenMap));
if (Math.abs(angle.imag) > 0.0001) {
... | @param {!string} formula
@param {undefined|!number} time
@param {!boolean} warn
@returns {undefined|!number} | parseTimeFormula | javascript | Strilanc/Quirk | src/gates/ParametrizedRotationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ParametrizedRotationGates.js | Apache-2.0 |
function badFormulaDetector(args) {
if (typeof args.gate.param === 'number') {
return args.gate.param;
} else if (typeof args.gate.param === 'string') {
for (let t of [0.01, 0.63, 0.98]) {
if (parseTimeFormula(args.gate.param, t, false) === undefined) {
return 'bad\nf... | @param {!GateCheckArgs} args
@returns {undefined|!string} | badFormulaDetector | javascript | Strilanc/Quirk | src/gates/ParametrizedRotationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ParametrizedRotationGates.js | Apache-2.0 |
function angleClicker(quantityName) {
return oldGate => {
let txt = prompt(
`Enter a formula to use for the ${quantityName}.\n` +
"\n" +
"The formula can depend on the time variable t.\n" +
"Time t starts at -1, grows to +1 over time, then jumps back to -1.\n"... | @param {!string} quantityName
@returns {!function(gate: !Gate): !Gate} | angleClicker | javascript | Strilanc/Quirk | src/gates/ParametrizedRotationGates.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ParametrizedRotationGates.js | Apache-2.0 |
function probabilityStatTexture(ketTexture, controlTexture, rangeOffset, rangeLength) {
let trader = new WglTextureTrader(ketTexture);
trader.dontDeallocCurrentTexture();
let n = currentShaderCoder().vec2.arrayPowerSizeOfTexture(ketTexture);
trader.shadeAndTrade(tex => amplitudesToProbabilities(tex, co... | Derives conditional computational basis measurement probabilities from the state vector.
@param {!WglTexture} ketTexture The texture storing the wavefunction.
@param {!WglTexture} controlTexture A precomputed texture storing a control mask set to 1 for satisfying states.
@param {!int} rangeOffset Which wire the probab... | probabilityStatTexture | javascript | Strilanc/Quirk | src/gates/ProbabilityDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ProbabilityDisplay.js | Apache-2.0 |
function probabilityPixelsToColumnVector(pixels, span) {
let n = 1 << span;
// CAUTION: pixels may be longer than n due to the length rounding up to a multiple of 4.
let unity = 0;
for (let i = 0; i < n; i++) {
unity += pixels[i];
}
if (isNaN(unity) || unity < 0.000001) {
return... | Post-processes the pixels that come out of makeProbabilitySpanPipeline into a vector of normalized probabilities.
@param {!Float32Array} pixels
@param {!int} span
@returns {!Matrix} | probabilityPixelsToColumnVector | javascript | Strilanc/Quirk | src/gates/ProbabilityDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ProbabilityDisplay.js | Apache-2.0 |
function probabilityDataToJson(data) {
return {
probabilities: Seq.range(data.height()).map(k => Complex.realPartOf(data.cell(0, k))).toArray()
};
} | Produces the exported simulator data associated with a probability display.
@param {!Matrix} data
@returns {!{probabilities: !float[]}} | probabilityDataToJson | javascript | Strilanc/Quirk | src/gates/ProbabilityDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ProbabilityDisplay.js | Apache-2.0 |
function multiChanceGateMaker(span, builder) {
return shared_chanceGateMaker(builder).
setSerializedId("Chance" + span).
setStatTexturesMaker(ctx =>
probabilityStatTexture(ctx.stateTrader.currentTexture, ctx.controlsTexture, ctx.row, span)).
setStatPixelDataPostProcessor(pixels =... | @param {!GateBuilder} builder
@param {!int} span
@returns {!GateBuilder} | multiChanceGateMaker | javascript | Strilanc/Quirk | src/gates/ProbabilityDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/ProbabilityDisplay.js | Apache-2.0 |
function sampleFromDistribution(args) {
let probabilities = args.customStats;
let buf = probabilities.rawBuffer();
let r = args.painter.rng.random();
let n = probabilities.height();
//noinspection ForLoopThatDoesntUseLoopVariableJS
for (let i = 0; ; i++) {
let p = buf[i*2];
r -= ... | Looks up the simulated probability distribution and samples from it using the current graphics PRNG.
@param {!GateDrawParams} args
@returns {!{i: !number, p: !number}} | sampleFromDistribution | javascript | Strilanc/Quirk | src/gates/SampleDisplay.js | https://github.com/Strilanc/Quirk/blob/master/src/gates/SampleDisplay.js | Apache-2.0 |
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
} | @param {!number} x
@param {!number} y
@param {!number} z | constructor | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static op(a, b, numNum, axisNum, numAxis, axisAxis) {
let ca = Axis.classify(a);
let cb = Axis.classify(b);
if (ca && cb) {
return axisAxis(a, b);
}
if (!ca && !cb) {
return numNum(a, b);
}
if (ca) {
return axisNum(a, b);
... | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | op | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static times(u, v) {
return Axis.op(
u, v,
(a, b) => a*b,
(a, b) => new Axis(a.x*b, a.y*b, a.z*b),
(a, b) => new Axis(b.x*a, b.y*a, b.z*a),
(a, b) => { throw new DetailedError("Can't multiply axes.", {a, b}); });
} | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | times | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static add(u, v) {
return Axis.op(
u, v,
(a, b) => a+b,
(a, b) => { throw new DetailedError("Can't add axes to numbers.", {a, b}); },
(a, b) => { throw new DetailedError("Can't add axes to numbers.", {a, b}); },
(a, b) => new Axis(a.x + b.x, a.y + b.y,... | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | add | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static negate(u) {
return Axis.classify(u) ? new Axis(-u.x, -u.y, -u.z) : -u;
} | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | negate | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static subtract(u, v) {
return Axis.op(
u, v,
(a, b) => a - b,
(a, b) => { throw new DetailedError("Can't subtract axes and numbers.", {a, b}); },
(a, b) => { throw new DetailedError("Can't subtract axes and numbers.", {a, b}); },
(a, b) => new Axis(a.... | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | subtract | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static divide(u, v) {
return Axis.op(
u, v,
(a, b) => a / b,
(a, b) => new Axis(a.x/b, a.y/b, a.z/b),
(a, b) => { throw new DetailedError("Can't divide by an axis.", {a, b}); },
(a, b) => { throw new DetailedError("Can't divide by an axis.", {a, b}); }... | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | divide | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
static raisedTo(u, v) {
return Axis.op(
u, v,
(a, b) => Math.pow(a, b),
(a, b) => { throw new DetailedError("Can't raise an axis to a power.", {a, b}); },
(a, b) => { throw new DetailedError("Can't raise to an axis power.", {a, b}); },
(a, b) => { thro... | @param {!number|!Axis} a
@param {!number|!Axis} b
@param {!function(!number, !number): (!number|!Axis)} numNum
@param {!function(!Axis, !number): (!number|!Axis)} axisNum
@param {!function(!number, !Axis): (!number|!Axis)} numAxis
@param {!function(!Axis, !Axis): (!number|!Axis)} axisAxis
@returns {!number|!Axis} | raisedTo | javascript | Strilanc/Quirk | src/math/Axis.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Axis.js | Apache-2.0 |
constructor(real, imag) {
/**
* The real part of the Complex number. The 'a' in a + bi.
* @type {!number}
*/
this.real = real;
/**
* The imaginary part of the Complex number. The 'b' in a + bi.
* @type {!number}
*/
this.imag = imag;
... | @param {!number} real The real part of the Complex number. The 'a' in a + bi.
@param {!number} imag The imaginary part of the Complex number. The 'b' in a + bi. | constructor | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
isEqualTo(other) {
if (other instanceof Complex) {
return this.real === other.real && this.imag === other.imag;
}
if (typeof other === "number") {
return this.real === other && this.imag === 0;
}
return false;
} | Determines if the receiving complex value is equal to the given complex, integer, or float value.
This method returns false, instead of throwing, when given badly typed arguments.
@param {!number|!Complex|*} other
@returns {!boolean} | isEqualTo | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
isApproximatelyEqualTo(other, epsilon) {
if (other instanceof Complex || typeof other === "number") {
let d = this.minus(Complex.from(other));
return Math.abs(d.real) <= epsilon &&
Math.abs(d.imag) <= epsilon &&
d.abs() <= epsilon;
}
return... | Determines if the receiving complex value is near the given complex, integer, or float value.
This method returns false, instead of throwing, when given badly typed arguments.
@param {!number|!Complex|*} other
@param {!number} epsilon
@returns {!boolean} | isApproximatelyEqualTo | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static from(v) {
if (v instanceof Complex) {
return v;
}
if (typeof v === "number") {
return new Complex(v, 0);
}
throw new DetailedError("Unrecognized value type.", {v});
} | Wraps the given number into a Complex value (unless it's already a Complex value).
@param {!number|!Complex} v
@returns {!Complex} | from | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static polar(magnitude, phase) {
let [cos, sin] = Util.snappedCosSin(phase);
return new Complex(magnitude * cos, magnitude * sin);
} | Returns a complex number with the given magnitude and phase.
@param {!number} magnitude Distance from origin.
@param {!number} phase Phase in radians.
@returns {!Complex} | polar | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static realPartOf(v) {
if (v instanceof Complex) {
return v.real;
}
if (typeof v === "number") {
return v;
}
throw new DetailedError("Unrecognized value type.", {v});
} | Returns the real component of a Complex, integer, or float value.
@param {!number|!Complex} v
@returns {!number} | realPartOf | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static imagPartOf(v) {
if (v instanceof Complex) {
return v.imag;
}
if (typeof v === "number") {
return 0;
}
throw new DetailedError("Unrecognized value type.", {v});
} | Returns the imaginary component of a Complex value, or else 0 for integer and float values.
@param {!number|!Complex} v
@returns {!number} | imagPartOf | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
toString(format) {
format = format || Format.EXACT;
return format.allowAbbreviation ?
this._toString_allowSingleValue(format) :
this._toString_bothValues(format);
} | Returns a compact text representation of the receiving complex value.
@param {=Format} format
@returns {!string} | toString | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
_toString_allowSingleValue(format) {
if (Math.abs(this.imag) <= format.maxAbbreviationError) {
return format.formatFloat(this.real);
}
if (Math.abs(this.real) <= format.maxAbbreviationError) {
if (Math.abs(this.imag - 1) <= format.maxAbbreviationError) {
r... | @param {!Format} format
@returns {!string}
@private | _toString_allowSingleValue | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
_toString_bothValues(format) {
let separator = this.imag >= 0 ? "+" : "-";
let imagFactor = format.allowAbbreviation && Math.abs(Math.abs(this.imag) - 1) <= format.maxAbbreviationError ?
"" :
format.formatFloat(Math.abs(this.imag));
let prefix = format.allowAbbreviation |... | @param {!Format} format
@returns {!string}
@private | _toString_bothValues | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static parse(text) {
return Complex.from(parseFormula(text, PARSE_COMPLEX_TOKEN_MAP_DEG));
} | Parses a complex number from an infix arithmetic expression.
@param {!string} text
@returns {!Complex} | parse | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
norm2() {
return this.real * this.real + this.imag * this.imag;
} | Returns the squared euclidean length of the receiving complex value.
@returns {!number} | norm2 | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
abs() {
return Math.sqrt(this.norm2());
} | Returns the euclidean length of the receiving complex value.
@returns {!number} | abs | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
conjugate() {
return new Complex(this.real, -this.imag);
} | Returns the complex conjugate of the receiving complex value, with the same real part but a negated imaginary part.
@returns {!Complex} | conjugate | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
neg() {
return new Complex(-this.real, -this.imag);
} | Returns the negation of this complex value.
@returns {!Complex} | neg | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
unit() {
let m = this.norm2();
if (m < 0.00001) {
return Complex.polar(1, this.phase());
}
return this.dividedBy(Math.sqrt(m));
} | Returns a unit complex value parallel to the receiving complex value.
Zero defaults to having the unit vector 1+0i.
@returns {!Complex} | unit | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
plus(v) {
let c = Complex.from(v);
return new Complex(this.real + c.real, this.imag + c.imag);
} | Returns the sum of the receiving complex value plus the given value.
@param {!number|!Complex} v
@returns {!Complex} | plus | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
minus(v) {
let c = Complex.from(v);
return new Complex(this.real - c.real, this.imag - c.imag);
} | Returns the difference from the receiving complex value to the given value.
@param {!number|!Complex} v
@returns {!Complex} | minus | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
times(v) {
let c = Complex.from(v);
return new Complex(
this.real * c.real - this.imag * c.imag,
this.real * c.imag + this.imag * c.real);
} | Returns the product of the receiving complex value times the given value.
@param {!number|!Complex} v
@returns {!Complex} | times | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
dividedBy(v) {
let c = Complex.from(v);
let d = c.norm2();
if (d === 0) {
throw new Error("Division by Zero");
}
let n = this.times(c.conjugate());
return new Complex(n.real / d, n.imag / d);
} | Returns the ratio of the receiving complex value to the given value.
@param {!number|!Complex} v
@returns {!Complex} | dividedBy | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
sqrts() {
let [r, i] = [this.real, this.imag];
let m = Math.sqrt(Math.sqrt(r*r + i*i));
if (m === 0) {
return [Complex.ZERO];
}
if (i === 0 && r < 0) {
return [new Complex(0, m), new Complex(0, -m)]
}
let a = this.phase() / 2;
let ... | Returns the ratio of the receiving complex value to the given value.
@param {!number|!Complex} v
@returns {!Complex} | sqrts | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
exp() {
return Complex.polar(Math.exp(this.real), this.imag);
} | Returns the result of raising Euler's constant to the receiving complex value.
@returns {!Complex} | exp | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
ln() {
return new Complex(Math.log(this.abs()), this.phase());
} | Returns the natural logarithm of the receiving complex value.
@returns {!Complex} | ln | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
raisedTo(exponent) {
if (exponent === 0.5 && this.imag === 0 && this.real >= 0) {
return new Complex(Math.sqrt(this.real), 0);
}
if (Complex.ZERO.isEqualTo(exponent)) {
return Complex.ONE;
}
if (this.isEqualTo(Complex.ZERO)) {
return Complex.ZE... | Returns the result of raising the receiving complex value to the given complex exponent.
@param {!number|!Complex} exponent
@returns {!Complex} | raisedTo | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
static rootsOfQuadratic(a, b, c) {
a = Complex.from(a);
b = Complex.from(b);
c = Complex.from(c);
if (a.isEqualTo(0)) {
if (!b.isEqualTo(0)) {
return [c.times(-1).dividedBy(b)];
}
if (!c.isEqualTo(0)) {
return [];
... | Returns the distinct roots of the quadratic, or linear, equation. | rootsOfQuadratic | javascript | Strilanc/Quirk | src/math/Complex.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Complex.js | Apache-2.0 |
function _mergeScientificFloatTokens(tokens) {
tokens = [...tokens];
for (let i = tokens.indexOf('e', 1); i !== -1; i = tokens.indexOf('e', i + 1)) {
let s = i - 1;
let e = i + 1;
if (!tokens[s].match(/[0-9]/)) {
continue;
}
if ((tokens[e] + '').match(/[+-]/))... | @param {!Array.<!String>} tokens
@returns {!Array.<!String>}
@private | _mergeScientificFloatTokens | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
function _tokenize(text) {
let tokens = seq(text.toLowerCase().split(/\s/)).
flatMap(part => seq(part).
segmentBy(e => {
if (e.trim() === '') {
return " ";
}
if (e.match(/[\.0-9]/)) {
return "#";
... | @param {!String} text
@returns {!Array.<!String>}
@private | _tokenize | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
function _translate_token(token, tokenMap) {
if (token.match(/[0-9]+(\.[0-9]+)?/)) {
return parseFloat(token);
}
if (tokenMap.has(token)) {
return tokenMap.get(token);
}
throw new DetailedError("Unrecognized token", {token});
} | @param {!string} token
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {!string|T|!{unary_action: undefined|!function(T):T, binary_action: undefined|!function(T, T): T}}
@template T
@private | _translate_token | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
function parseFormula(text, tokenMap) {
let tokens = _tokenize(text).map(e => _translate_token(e, tokenMap));
// Cut off trailing operation, so parse fails less often as users are typing.
if (tokens.length > 0 && tokens[tokens.length - 1].priority !== undefined) {
tokens = tokens.slice(0, tokens.le... | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | parseFormula | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
apply = op => {
if (op === "(") {
throw new DetailedError("Bad expression: unmatched '('", {text});
}
if (vals.length < 2) {
throw new DetailedError("Bad expression: operated on nothing", {text});
}
let b = vals.pop();
let a = vals.pop();
v... | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | apply | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
apply = op => {
if (op === "(") {
throw new DetailedError("Bad expression: unmatched '('", {text});
}
if (vals.length < 2) {
throw new DetailedError("Bad expression: operated on nothing", {text});
}
let b = vals.pop();
let a = vals.pop();
v... | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | apply | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
closeParen = () => {
while (true) {
if (ops.length === 0) {
throw new DetailedError("Bad expression: unmatched ')'", {text});
}
let op = ops.pop();
if (op === "(") {
break;
}
apply(op);
}
} | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | closeParen | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
closeParen = () => {
while (true) {
if (ops.length === 0) {
throw new DetailedError("Bad expression: unmatched ')'", {text});
}
let op = ops.pop();
if (op === "(") {
break;
}
apply(op);
}
} | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | closeParen | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
burnOps = w => {
while (ops.length > 0 && vals.length >= 2 && vals[vals.length - 1] !== undefined) {
let top = ops[ops.length - 1];
if (top.w === undefined || top.w < w) {
break;
}
apply(ops.pop());
}
} | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | burnOps | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
burnOps = w => {
while (ops.length > 0 && vals.length >= 2 && vals[vals.length - 1] !== undefined) {
let top = ops[ops.length - 1];
if (top.w === undefined || top.w < w) {
break;
}
apply(ops.pop());
}
} | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | burnOps | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
feedOp = (couldBeBinary, token) => {
// Implied multiplication?
let mul = tokenMap.get("*");
if (couldBeBinary && token.binary_action === undefined && token !== ")") {
burnOps(mul.priority);
ops.push({f: mul.binary_action, w: mul.priority});
}
if (couldBe... | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | feedOp | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
feedOp = (couldBeBinary, token) => {
// Implied multiplication?
let mul = tokenMap.get("*");
if (couldBeBinary && token.binary_action === undefined && token !== ")") {
burnOps(mul.priority);
ops.push({f: mul.binary_action, w: mul.priority});
}
if (couldBe... | Parses a value from an infix arithmetic expression.
@param {!string} text
@param {!Map.<!string, T|!string|!number>} tokenMap
@returns {T}
@template T | feedOp | javascript | Strilanc/Quirk | src/math/FormulaParser.js | https://github.com/Strilanc/Quirk/blob/master/src/math/FormulaParser.js | Apache-2.0 |
constructor(width, height, buffer) {
if (width*height*2 !== buffer.length) {
throw new DetailedError("width*height*2 !== buffer.length", {width, height, len: buffer.length});
}
/**
* @type {int}
* @private
*/
this._width = width;
/**
... | @param {int} width
@param {int} height
@param {!Float64Array|!Float32Array} buffer Complex value data, packed row-wise with real and imaginary
coefficients interleaved. | constructor | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
cell(col, row) {
if (col < 0 || row < 0 || col >= this._width || row >= this._height) {
throw new DetailedError("Cell out of range", {col, row, width: this._width, height: this._height});
}
let i = (this._width*row + col)*2;
return new Complex(this._buffer[i], this._buffer[i ... | @param {int} col
@param {int} row
@returns {!Complex} | cell | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
toReadableJson() {
return seq(this.rows()).map(complexVectorToReadableJson).toArray();
} | Encodes the matrix into JSON that could easily be read by humans or processed by external programs.
@returns {*} | toReadableJson | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
static fromRows(rows) {
Util.need(Array.isArray(rows) && rows.every(Array.isArray), "array rows", rows);
Util.need(rows.length > 0, "non-zero height", arguments);
let seqRows = seq(rows);
let h = rows.length;
let w = seqRows.map(e => e.length).distinct().single(null);
if... | @param rows {!Array.<!Array.<Complex>>} The rows of complex coefficients making up the matrix. | fromRows | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
isEqualTo(obj) {
if (this === obj) {
return true;
}
if (!(obj instanceof Matrix)) {
return false;
}
/** @type {!Matrix} */
let other = obj;
return this._width === other._width &&
this._height === other._height &&
Se... | Determines if the receiving matrix is equal to the given matrix.
This method returns false, instead of throwing, when given badly typed arguments.
@param {!Matrix|*} obj
@returns {!boolean} | isEqualTo | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
isApproximatelyEqualTo(other, epsilon) {
return other instanceof Matrix &&
this._width === other._width &&
this._height === other._height &&
Math.sqrt(this.minus(other).norm2()) <= epsilon;
} | Determines if the receiving matrix is approximately equal to the given matrix.
@param {!Matrix|*} other
@param {!number} epsilon Maximum distance between the two matrices.
@returns {!boolean} | isApproximatelyEqualTo | javascript | Strilanc/Quirk | src/math/Matrix.js | https://github.com/Strilanc/Quirk/blob/master/src/math/Matrix.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.