diff --git a/public/arms.html b/public/arms.html index 3bca1a0..6c73b19 100644 --- a/public/arms.html +++ b/public/arms.html @@ -24,18 +24,47 @@

You have selected: Arms

+ +
+

Select muscle group for workout:

+ +
+ +
+ +
00:00:00
diff --git a/public/chest.html b/public/chest.html index 0f69017..f7da6f3 100644 --- a/public/chest.html +++ b/public/chest.html @@ -25,18 +25,46 @@

You have selected: Chest

+
+

Select muscle group for workout:

+ +
+ +
+ +
00:00:00
diff --git a/public/css/arms.css b/public/css/arms.css index c911eac..a6251a3 100644 --- a/public/css/arms.css +++ b/public/css/arms.css @@ -1,3 +1,8 @@ +.button { + padding: 0; + margin: 0; +} + .body { font-family: 'IBM Plex Sans Hebrew', sans-serif; font-weight: normal; @@ -48,10 +53,109 @@ background-color: #111; } -#playButton { - display: block; +.muscle { + padding: 0 20px; +} + +.muscle h3{ + position: relative; + font-family: 'IBM Plex Sans Hebrew', sans-serif; + font-style: normal; + font-weight: normal; + font-size: 200%; + line-height: 115px; + text-align: center; + letter-spacing: -0.017em; + + padding-top: 50px; + + color: #000000; +} + + +.muscle ul { + position: relative; + padding:0; + margin:0; + } + +.muscle li{ + float: left; + width: calc((100% - 20px*2)/3); + height:auto; + list-style-type: none; + background-color: #333; + margin-right: 20px; + margin-bottom: none; + position: relative; + text-align: center; + border-radius: 20px; + + box-shadow: 0px 0px 10px rgba(0,0,0,.5); + transition: transform .2s; +} + +.muscle li:last-of-type{ + margin-right: 0px; +} + +.imgfilter{ + position: absolute; + top: 0; + height: 100%; + width: 100%; + background-color: #00000060; + border-radius: 20px; +} + +.muscle li p1{ + color: #FFFFFF; + font-family: 'IBM Plex Sans Hebrew', sans-serif; + + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + +} + +.muscle li:hover { + transform: scale(1.05); +} + +.muscle li img{ + max-width: 100%; +} + +#container{ + padding: 20px; + width: 100%; + height: 20%; + text-align: center; + display: none; +} +.stopwatch{ + padding-top: 20px; + text-align: center; +} + +.buttonPlay { + display: inline-block; } #pauseButton { display: none; +} + +.buttonReset { + +} + +.stopwatch button { + height: 100px; +} + +.stopwatch img{ + max-height: 100%; + max-width: 100% } \ No newline at end of file diff --git a/public/css/chest.css b/public/css/chest.css index c911eac..a6251a3 100644 --- a/public/css/chest.css +++ b/public/css/chest.css @@ -1,3 +1,8 @@ +.button { + padding: 0; + margin: 0; +} + .body { font-family: 'IBM Plex Sans Hebrew', sans-serif; font-weight: normal; @@ -48,10 +53,109 @@ background-color: #111; } -#playButton { - display: block; +.muscle { + padding: 0 20px; +} + +.muscle h3{ + position: relative; + font-family: 'IBM Plex Sans Hebrew', sans-serif; + font-style: normal; + font-weight: normal; + font-size: 200%; + line-height: 115px; + text-align: center; + letter-spacing: -0.017em; + + padding-top: 50px; + + color: #000000; +} + + +.muscle ul { + position: relative; + padding:0; + margin:0; + } + +.muscle li{ + float: left; + width: calc((100% - 20px*2)/3); + height:auto; + list-style-type: none; + background-color: #333; + margin-right: 20px; + margin-bottom: none; + position: relative; + text-align: center; + border-radius: 20px; + + box-shadow: 0px 0px 10px rgba(0,0,0,.5); + transition: transform .2s; +} + +.muscle li:last-of-type{ + margin-right: 0px; +} + +.imgfilter{ + position: absolute; + top: 0; + height: 100%; + width: 100%; + background-color: #00000060; + border-radius: 20px; +} + +.muscle li p1{ + color: #FFFFFF; + font-family: 'IBM Plex Sans Hebrew', sans-serif; + + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + +} + +.muscle li:hover { + transform: scale(1.05); +} + +.muscle li img{ + max-width: 100%; +} + +#container{ + padding: 20px; + width: 100%; + height: 20%; + text-align: center; + display: none; +} +.stopwatch{ + padding-top: 20px; + text-align: center; +} + +.buttonPlay { + display: inline-block; } #pauseButton { display: none; +} + +.buttonReset { + +} + +.stopwatch button { + height: 100px; +} + +.stopwatch img{ + max-height: 100%; + max-width: 100% } \ No newline at end of file diff --git a/public/css/legs.css b/public/css/legs.css index a6251a3..efc1b9d 100644 --- a/public/css/legs.css +++ b/public/css/legs.css @@ -104,7 +104,7 @@ top: 0; height: 100%; width: 100%; - background-color: #00000060; + background-color: #000000; border-radius: 20px; } @@ -134,21 +134,27 @@ text-align: center; display: none; } + .stopwatch{ padding-top: 20px; text-align: center; + + font-family: 'IBM Plex Sans Hebrew', sans-serif; + font-size: 150%; } -.buttonPlay { - display: inline-block; +#playButton { + display: inline-block; } #pauseButton { display: none; } -.buttonReset { - +#resetButton { + display: inline-block; + padding: 0; + margin: 0; } .stopwatch button { diff --git a/public/index.html b/public/index.html index 07a7a16..a1a90b7 100644 --- a/public/index.html +++ b/public/index.html @@ -9,6 +9,13 @@ + + + + + + + @@ -70,11 +77,11 @@

Select muscle group for workout:

- + +
diff --git a/public/javascripts/index.js b/public/javascripts/index.js index f3e5fc8..a37a1cc 100644 --- a/public/javascripts/index.js +++ b/public/javascripts/index.js @@ -1,63 +1,101 @@ const defaultWidth = 640; const defaultHeight = 480; +let poseNet, brain, pose; -setTimeout(function () { - function update(stream) { - document.querySelector('video').src = stream.url; - } - - if (navigator.mediaDevices.getUserMedia) { - navigator.mediaDevices.getUserMedia({ video: true }) - .then(function (stream) { - video.srcObject = stream; - startPosing(); - }) - .catch(function (err0r) { - console.log("Something went wrong!"); - }); - } -}, 1000) +let state = 'waiting'; +let targetLabel; +let options = { + inputs: 34, + outputs: 4, + task: 'classification', + debug: true +} -async function startPosing() { +const modelInfo = { + model: '../models/model.json', + metadata: '../models/model_meta.json', + weights: '../models/model.weights.bin', +}; - const detectorConfig = {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER}; - const detector = await poseDetection.createDetector(poseDetection.SupportedModels.MoveNet, detectorConfig); +let videoElement = document.getElementById('video'); - canvas.width = $("#video").innerWidth(); - canvas.height = $("#video").innerHeight(); +//brain = ml5.neuralNetwork(options); +//brain.load(modelInfo, brainLoaded); - // Video loop - var fps = 1000; - var now; - var then = Date.now(); - var interval = 1000/fps; - window.delta = 0; +function brainLoaded() { + console.log('pose classification ready!'); +} - let neckArray = []; +function modelLoaded() { + console.log('poseNet ready'); +} - function loop() { - requestAnimationFrame(loop); - now = Date.now(); - delta = now - then; +function gotPoses(poses) { + /*if (poses.length > 0) { + let pose = poses[0].keypoints; + if (state == 'collecting') { + let inputs = []; + for (let i = 0; i < pose.length; i++) { + let x = pose[i].x; + let y = poses[i].y; + inputs.push(x); + inputs.push(y); + } + let target = [targetLabel]; + console.log(inputs); + brain.addData(inputs, target); + } + }*/ +} - if (delta > interval) { - then = now - (delta % interval); - ctx.clearRect(0, 0, canvas.width, canvas.height); - update(); + +let inputs = []; + +function classifyPose(pose) { + if (pose) { + let inputs = []; + for (let p of pose) { + let x = p.x; + let y = p.y; + inputs.push(x); + inputs.push(y); } + //brain.classify(inputs, gotResult); } - loop(); +} +function gotResult(error, results) { + if(error){ + console.error(error); + return; + } + //console.log(results); + if (results[0].confidence > 0.75) { + poseLabel = results[0].label.toUpperCase(); + //console.log(poseLabel); + } + classifyPose(); +} +async function startPosing() { + + // Set up detector + const detectorConfig = {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER}; + const detector = await poseDetection.createDetector(poseDetection.SupportedModels.MoveNet, detectorConfig); + + canvas.width = $("#video").innerWidth(); + canvas.height = $("#video").innerHeight(); + + // Count function countReps() { let lag = 5; let threshold = 3.5; let influence = 0.5; let signals = new Array(neckArray.length).fill(0); let filteredY = [...Array(lag + 1).keys()]; - let avgFilter = null; + let avgFilter = neckArray.slice(0, ); let stdFilter = null; } @@ -68,9 +106,13 @@ async function startPosing() { // Update function async function update () { - let videoElement = document.getElementById('video'); let poses = await detector.estimatePoses(videoElement); + gotPoses(poses); + if (poses.length > 0){ + pose = poses[0].keypoints; + } + detector.reset(); ctx.clearRect(0, 0, canvas.width, canvas.height) @@ -81,8 +123,15 @@ async function startPosing() { let body = {} + inputs = []; + + + classifyPose(points) // Convert points to body joints for (let p of points) { + inputs.push(p.x); + inputs.push(p.y); + p.x = (canvas.width-p.x - (canvas.width-defaultWidth)) * (canvas.width/defaultWidth); p.y = p.y * (canvas.height/defaultHeight) body[p.name] = p; @@ -108,7 +157,7 @@ async function startPosing() { y: (body["left_shoulder"].y + body["right_shoulder"].y) / 2 } neckArray.push(neck.y); - console.log(countReps()); + //console.log(countReps()); let dick = { x: (body["left_hip"].x + body["right_hip"].x) / 2, y: (body["left_hip"].y + body["right_hip"].y) / 2 @@ -149,29 +198,7 @@ async function startPosing() { drawText(text, canvas.width/2, canvas.height/2, "100px Arial", color, "center", "middle") - // Draw the skeleton - drawLine(joints["left_ear"].x, joints["left_ear"].y, joints["left_eye"].x, joints["left_eye"].y, "lime", 4) - drawLine(joints["left_eye"].x, joints["left_eye"].y, joints["nose"].x, joints["nose"].y, "lime", 4) - drawLine(joints["nose"].x, joints["nose"].y, joints["right_eye"].x, joints["right_eye"].y, "lime", 4) - drawLine(joints["right_eye"].x, joints["right_eye"].y, joints["right_ear"].x, joints["right_ear"].y, "lime", 4) - - drawLine(joints["left_wrist"].x, joints["left_wrist"].y, joints["left_elbow"].x, joints["left_elbow"].y, "lime", 4) - drawLine(joints["left_elbow"].x, joints["left_elbow"].y, joints["left_shoulder"].x, joints["left_shoulder"].y, "lime", 4) - - drawLine(joints["right_wrist"].x, joints["right_wrist"].y, joints["right_elbow"].x, joints["right_elbow"].y, "lime", 4) - drawLine(joints["right_elbow"].x, joints["right_elbow"].y, joints["right_shoulder"].x, joints["right_shoulder"].y, "lime", 4) - - drawLine(joints["left_shoulder"].x, joints["left_shoulder"].y, joints["right_shoulder"].x, joints["right_shoulder"].y, "lime", 4) - drawLine(joints["left_hip"].x, joints["left_hip"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) - - drawLine(joints["left_shoulder"].x, joints["left_shoulder"].y, joints["left_hip"].x, joints["left_hip"].y, "lime", 4) - drawLine(joints["right_shoulder"].x, joints["right_shoulder"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) - - drawLine(joints["left_knee"].x, joints["left_knee"].y, joints["left_hip"].x, joints["left_hip"].y, "lime", 4) - drawLine(joints["right_knee"].x, joints["right_knee"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) - - drawLine(joints["left_knee"].x, joints["left_knee"].y, joints["left_ankle"].x, joints["left_ankle"].y, "lime", 4) - drawLine(joints["right_knee"].x, joints["right_knee"].y, joints["right_ankle"].x, joints["right_ankle"].y, "lime", 4) + drawSkeleton(joints); // Draw the joints for (let id of Object.keys(joints)) { @@ -192,4 +219,71 @@ async function startPosing() { } + // Video loop + var fps = 1000; + var now; + var then = Date.now(); + var interval = 1000/fps; + window.delta = 0; + + let neckArray = []; + + function loop() { + requestAnimationFrame(loop); + + now = Date.now(); + delta = now - then; + + if (delta > interval) { + then = now - (delta % interval); + + ctx.clearRect(0, 0, canvas.width, canvas.height); + update(); + } + } + loop(); +} + + +function drawSkeleton(joints) { + // Draw the skeleton + drawLine(joints["left_ear"].x, joints["left_ear"].y, joints["left_eye"].x, joints["left_eye"].y, "lime", 4) + drawLine(joints["left_eye"].x, joints["left_eye"].y, joints["nose"].x, joints["nose"].y, "lime", 4) + drawLine(joints["nose"].x, joints["nose"].y, joints["right_eye"].x, joints["right_eye"].y, "lime", 4) + drawLine(joints["right_eye"].x, joints["right_eye"].y, joints["right_ear"].x, joints["right_ear"].y, "lime", 4) + + drawLine(joints["left_wrist"].x, joints["left_wrist"].y, joints["left_elbow"].x, joints["left_elbow"].y, "lime", 4) + drawLine(joints["left_elbow"].x, joints["left_elbow"].y, joints["left_shoulder"].x, joints["left_shoulder"].y, "lime", 4) + + drawLine(joints["right_wrist"].x, joints["right_wrist"].y, joints["right_elbow"].x, joints["right_elbow"].y, "lime", 4) + drawLine(joints["right_elbow"].x, joints["right_elbow"].y, joints["right_shoulder"].x, joints["right_shoulder"].y, "lime", 4) + + drawLine(joints["left_shoulder"].x, joints["left_shoulder"].y, joints["right_shoulder"].x, joints["right_shoulder"].y, "lime", 4) + drawLine(joints["left_hip"].x, joints["left_hip"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) + + drawLine(joints["left_shoulder"].x, joints["left_shoulder"].y, joints["left_hip"].x, joints["left_hip"].y, "lime", 4) + drawLine(joints["right_shoulder"].x, joints["right_shoulder"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) + + drawLine(joints["left_knee"].x, joints["left_knee"].y, joints["left_hip"].x, joints["left_hip"].y, "lime", 4) + drawLine(joints["right_knee"].x, joints["right_knee"].y, joints["right_hip"].x, joints["right_hip"].y, "lime", 4) + + drawLine(joints["left_knee"].x, joints["left_knee"].y, joints["left_ankle"].x, joints["left_ankle"].y, "lime", 4) + drawLine(joints["right_knee"].x, joints["right_knee"].y, joints["right_ankle"].x, joints["right_ankle"].y, "lime", 4) } + +setTimeout(function () { + function update(stream) { + document.querySelector('video').src = stream.url; + } + + if (navigator.mediaDevices.getUserMedia) { + navigator.mediaDevices.getUserMedia({ video: true }) + .then(function (stream) { + video.srcObject = stream; + startPosing(); // START POSING + }) + .catch(function (err0r) { + console.log("Something went wrong!"); + }); + } +}, 1000) diff --git a/public/javascripts/ml5.min.js b/public/javascripts/ml5.min.js new file mode 100644 index 0000000..9a96421 --- /dev/null +++ b/public/javascripts/ml5.min.js @@ -0,0 +1,72 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ml5=e():t.ml5=e()}(window,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.r=function(t){Object.defineProperty(t,"__esModule",{value:!0})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/",n(n.s=967)}([function(t,e,n){"use strict";n.r(e),function(t,r,i,o){n.d(e,"AdadeltaOptimizer",function(){return wl}),n.d(e,"AdagradOptimizer",function(){return xl}),n.d(e,"AdamOptimizer",function(){return _l}),n.d(e,"AdamaxOptimizer",function(){return kl}),n.d(e,"DataStorage",function(){return Hr}),n.d(e,"ENV",function(){return h}),n.d(e,"Environment",function(){return f}),n.d(e,"KernelBackend",function(){return $r}),n.d(e,"MomentumOptimizer",function(){return El}),n.d(e,"Optimizer",function(){return yl}),n.d(e,"RMSPropOptimizer",function(){return Ol}),n.d(e,"Rank",function(){return gt}),n.d(e,"Reduction",function(){return Iu}),n.d(e,"SGDOptimizer",function(){return Sl}),n.d(e,"Tensor",function(){return pt}),n.d(e,"TensorBuffer",function(){return lt}),n.d(e,"Variable",function(){return mt}),n.d(e,"abs",function(){return Lo}),n.d(e,"acos",function(){return Bo}),n.d(e,"acosh",function(){return Uo}),n.d(e,"add",function(){return Is}),n.d(e,"addN",function(){return Ds}),n.d(e,"addStrict",function(){return js}),n.d(e,"all",function(){return cs}),n.d(e,"any",function(){return ls}),n.d(e,"argMax",function(){return fs}),n.d(e,"argMin",function(){return ds}),n.d(e,"asin",function(){return Wo}),n.d(e,"asinh",function(){return qo}),n.d(e,"atan",function(){return Vo}),n.d(e,"atan2",function(){return Rs}),n.d(e,"atanh",function(){return Ho}),n.d(e,"avgPool",function(){return es}),n.d(e,"backend",function(){return Ke}),n.d(e,"backend_util",function(){return ci}),n.d(e,"basicLSTMCell",function(){return vu}),n.d(e,"batchNorm",function(){return Na}),n.d(e,"batchNorm2d",function(){return Ta}),n.d(e,"batchNorm3d",function(){return Ia}),n.d(e,"batchNorm4d",function(){return Da}),n.d(e,"batchNormalization",function(){return Ma}),n.d(e,"batchNormalization2d",function(){return Oa}),n.d(e,"batchNormalization3d",function(){return Aa}),n.d(e,"batchNormalization4d",function(){return Ca}),n.d(e,"batchToSpaceND",function(){return Jn}),n.d(e,"browser",function(){return al}),n.d(e,"buffer",function(){return Xn}),n.d(e,"cast",function(){return Zn}),n.d(e,"ceil",function(){return $o}),n.d(e,"clipByValue",function(){return Go}),n.d(e,"clone",function(){return Qn}),n.d(e,"complex",function(){return hn}),n.d(e,"concat",function(){return In}),n.d(e,"concat1d",function(){return Dn}),n.d(e,"concat2d",function(){return jn}),n.d(e,"concat3d",function(){return Rn}),n.d(e,"concat4d",function(){return Fn}),n.d(e,"conv1d",function(){return Pa}),n.d(e,"conv2d",function(){return za}),n.d(e,"conv2dDerFilter",function(){return Ba}),n.d(e,"conv2dTranspose",function(){return qa}),n.d(e,"conv3d",function(){return La}),n.d(e,"cos",function(){return Ko}),n.d(e,"cosh",function(){return Xo}),n.d(e,"cumsum",function(){return tr}),n.d(e,"customGrad",function(){return Ur}),n.d(e,"deprecationWarn",function(){return De}),n.d(e,"depthToSpace",function(){return er}),n.d(e,"depthwiseConv2d",function(){return Ua}),n.d(e,"disableDeprecationWarnings",function(){return Ie}),n.d(e,"dispose",function(){return ze}),n.d(e,"disposeVariables",function(){return je}),n.d(e,"div",function(){return Fs}),n.d(e,"divStrict",function(){return Ps}),n.d(e,"dot",function(){return Ha}),n.d(e,"dropout",function(){return Nu}),n.d(e,"elu",function(){return ou}),n.d(e,"enableDebugMode",function(){return Te}),n.d(e,"enableProdMode",function(){return Ne}),n.d(e,"environment",function(){return m}),n.d(e,"equal",function(){return ws}),n.d(e,"equalStrict",function(){return xs}),n.d(e,"erf",function(){return Yo}),n.d(e,"exp",function(){return Jo}),n.d(e,"expandDims",function(){return nr}),n.d(e,"expm1",function(){return Zo}),n.d(e,"eye",function(){return rr}),n.d(e,"fft",function(){return ku}),n.d(e,"fill",function(){return An}),n.d(e,"findBackend",function(){return He}),n.d(e,"findBackendFactory",function(){return $e}),n.d(e,"floor",function(){return Qo}),n.d(e,"floorDiv",function(){return zs}),n.d(e,"frame",function(){return Ru}),n.d(e,"fused",function(){return ic}),n.d(e,"gather",function(){return mu}),n.d(e,"gatherND",function(){return Mu}),n.d(e,"getBackend",function(){return qe}),n.d(e,"grad",function(){return Fr}),n.d(e,"grads",function(){return Pr}),n.d(e,"greater",function(){return _s}),n.d(e,"greaterEqual",function(){return ks}),n.d(e,"greaterEqualStrict",function(){return Ss}),n.d(e,"greaterStrict",function(){return Es}),n.d(e,"hammingWindow",function(){return ju}),n.d(e,"hannWindow",function(){return Du}),n.d(e,"ifft",function(){return Su}),n.d(e,"imag",function(){return mn}),n.d(e,"image",function(){return nc}),n.d(e,"io",function(){return nl}),n.d(e,"irfft",function(){return Ou}),n.d(e,"isFinite",function(){return fa}),n.d(e,"isInf",function(){return la}),n.d(e,"isNaN",function(){return ca}),n.d(e,"keep",function(){return Le}),n.d(e,"leakyRelu",function(){return au}),n.d(e,"less",function(){return Os}),n.d(e,"lessEqual",function(){return As}),n.d(e,"lessEqualStrict",function(){return Cs}),n.d(e,"lessStrict",function(){return Ms}),n.d(e,"linalg",function(){return Yu}),n.d(e,"linspace",function(){return Cn}),n.d(e,"localResponseNormalization",function(){return fu}),n.d(e,"log",function(){return ta}),n.d(e,"log1p",function(){return ea}),n.d(e,"logSigmoid",function(){return na}),n.d(e,"logSoftmax",function(){return Vr}),n.d(e,"logSumExp",function(){return hs}),n.d(e,"logicalAnd",function(){return Qs}),n.d(e,"logicalNot",function(){return tu}),n.d(e,"logicalOr",function(){return eu}),n.d(e,"logicalXor",function(){return nu}),n.d(e,"losses",function(){return $u}),n.d(e,"matMul",function(){return Va}),n.d(e,"math",function(){return il}),n.d(e,"max",function(){return ps}),n.d(e,"maxPool",function(){return ts}),n.d(e,"maximum",function(){return Ls}),n.d(e,"maximumStrict",function(){return Bs}),n.d(e,"mean",function(){return ms}),n.d(e,"memory",function(){return Re}),n.d(e,"min",function(){return gs}),n.d(e,"minimum",function(){return Us}),n.d(e,"minimumStrict",function(){return Ws}),n.d(e,"mod",function(){return qs}),n.d(e,"modStrict",function(){return Vs}),n.d(e,"moments",function(){return vs}),n.d(e,"movingAverage",function(){return yu}),n.d(e,"mul",function(){return Hs}),n.d(e,"mulStrict",function(){return $s}),n.d(e,"multiRNNCell",function(){return bu}),n.d(e,"multinomial",function(){return ir}),n.d(e,"neg",function(){return ra}),n.d(e,"nextFrame",function(){return Nl}),n.d(e,"norm",function(){return du}),n.d(e,"notEqual",function(){return Ns}),n.d(e,"notEqualStrict",function(){return Ts}),n.d(e,"oneHot",function(){return or}),n.d(e,"ones",function(){return En}),n.d(e,"onesLike",function(){return Nn}),n.d(e,"op",function(){return dn}),n.d(e,"outerProduct",function(){return $a}),n.d(e,"pad",function(){return ar}),n.d(e,"pad1d",function(){return sr}),n.d(e,"pad2d",function(){return ur}),n.d(e,"pad3d",function(){return cr}),n.d(e,"pad4d",function(){return lr}),n.d(e,"pool",function(){return ns}),n.d(e,"pow",function(){return Gs}),n.d(e,"powStrict",function(){return Ks}),n.d(e,"prelu",function(){return su}),n.d(e,"print",function(){return Yn}),n.d(e,"prod",function(){return ys}),n.d(e,"profile",function(){return Fe}),n.d(e,"rand",function(){return fr}),n.d(e,"randomNormal",function(){return dr}),n.d(e,"randomUniform",function(){return hr}),n.d(e,"range",function(){return Mn}),n.d(e,"ready",function(){return We}),n.d(e,"real",function(){return pn}),n.d(e,"reciprocal",function(){return ia}),n.d(e,"registerBackend",function(){return Ge}),n.d(e,"relu",function(){return uu}),n.d(e,"removeBackend",function(){return Ve}),n.d(e,"reshape",function(){return pr}),n.d(e,"reverse",function(){return Ga}),n.d(e,"reverse1d",function(){return Ka}),n.d(e,"reverse2d",function(){return Xa}),n.d(e,"reverse3d",function(){return Ya}),n.d(e,"reverse4d",function(){return Ja}),n.d(e,"rfft",function(){return Eu}),n.d(e,"round",function(){return oa}),n.d(e,"rsqrt",function(){return aa}),n.d(e,"scalar",function(){return bn}),n.d(e,"scatterND",function(){return _u}),n.d(e,"selu",function(){return cu}),n.d(e,"separableConv2d",function(){return Wa}),n.d(e,"serialization",function(){return ll}),n.d(e,"setBackend",function(){return Ue}),n.d(e,"setPlatform",function(){return Xe}),n.d(e,"setdiff1dAsync",function(){return xr}),n.d(e,"sigmoid",function(){return sa}),n.d(e,"sign",function(){return ua}),n.d(e,"signal",function(){return Fu}),n.d(e,"sin",function(){return da}),n.d(e,"sinh",function(){return ha}),n.d(e,"slice",function(){return rs}),n.d(e,"slice1d",function(){return is}),n.d(e,"slice2d",function(){return os}),n.d(e,"slice3d",function(){return as}),n.d(e,"slice4d",function(){return ss}),n.d(e,"softmax",function(){return qr}),n.d(e,"softplus",function(){return pa}),n.d(e,"spaceToBatchND",function(){return mr}),n.d(e,"sparseToDense",function(){return Cu}),n.d(e,"spectral",function(){return Au}),n.d(e,"split",function(){return Pn}),n.d(e,"sqrt",function(){return ma}),n.d(e,"square",function(){return ga}),n.d(e,"squaredDifference",function(){return Xs}),n.d(e,"squaredDifferenceStrict",function(){return Ys}),n.d(e,"squeeze",function(){return gr}),n.d(e,"stack",function(){return vr}),n.d(e,"step",function(){return va}),n.d(e,"stridedSlice",function(){return wu}),n.d(e,"sub",function(){return Js}),n.d(e,"subStrict",function(){return Zs}),n.d(e,"sum",function(){return bs}),n.d(e,"tan",function(){return ba}),n.d(e,"tanh",function(){return ya}),n.d(e,"tensor",function(){return gn}),n.d(e,"tensor1d",function(){return yn}),n.d(e,"tensor2d",function(){return wn}),n.d(e,"tensor3d",function(){return xn}),n.d(e,"tensor4d",function(){return _n}),n.d(e,"tensor5d",function(){return kn}),n.d(e,"tensor6d",function(){return Sn}),n.d(e,"tensor_util",function(){return Mt}),n.d(e,"test_util",function(){return gl}),n.d(e,"tidy",function(){return Pe}),n.d(e,"tile",function(){return br}),n.d(e,"time",function(){return Be}),n.d(e,"topk",function(){return xu}),n.d(e,"train",function(){return Cl}),n.d(e,"transpose",function(){return lu}),n.d(e,"truncatedNormal",function(){return yr}),n.d(e,"unsortedSegmentSum",function(){return gu}),n.d(e,"unstack",function(){return wr}),n.d(e,"util",function(){return rt}),n.d(e,"valueAndGrad",function(){return zr}),n.d(e,"valueAndGrads",function(){return Lr}),n.d(e,"variable",function(){return xt}),n.d(e,"variableGrads",function(){return Br}),n.d(e,"version_core",function(){return vl}),n.d(e,"webgl",function(){return bl}),n.d(e,"where",function(){return ru}),n.d(e,"whereAsync",function(){return iu}),n.d(e,"zeros",function(){return On}),n.d(e,"zerosLike",function(){return Tn}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var a=function(t,e){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function s(t,e){function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var u=function(){return(u=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function v(t,e,n){return Math.max(t,Math.min(e,n))}function b(t){return t%2==0?t:t+1}function y(t){for(var e=0,n=0;n=n?i():setTimeout(a,s)}};a()})}function T(t,e){for(var n=1,r=-1,i=0;i=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o}function I(t,e){var n=e.length;return w((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ta)&&1===t[a]&&(n.push(t[a]),r.push(a)),i[o]<=a&&o++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}}function j(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function R(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function F(t,e,n){if("float32"===e)for(var r=0;r=0;--r)n[r]=n[r+1]*t[r+1];return n}function Y(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=k(t)),n&&P(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function nt(t,e){return h.platform.fetch(t,e)}var rt=Object.freeze({shuffle:g,clamp:v,nearestLargerEven:b,sum:y,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r=this.shape[n]){var a="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(a)}n++}for(var s=t[t.length-1],u=0;u1)for(var c=0;c20){var l=3*s,f=Array.from(e.slice(0,l)),d=Array.from(e.slice(u-3*s,u));return"complex64"===r&&(f=ct(f),d=ct(d)),["["+f.map(function(t,e){return st(t,o[e],r)}).join(", ")+", ..., "+d.map(function(t,e){return st(t,o[u-3+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?ct(e):Array.from(e)).map(function(t,e){return st(t,o[e],r)}).join(", ")+"]"]}var h=n.slice(1),p=i.slice(1),m=i[0]*s,g=[];if(u>20){for(var v=0;v<3;v++){var b=(y=v*m)+m;g.push.apply(g,t(e.slice(y,b),h,r,p,o,!1))}for(g.push("..."),v=u-3;v0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return c(this,void 0,void 0,function(){var e,n;return l(this,function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var i={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.state.activeTape.push(i)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=At(t),r=new Set(n.map(function(t){return t.id})),i=0;i0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var o=this.scopedRun(function(){return i.startTape()},function(){return i.endTape()},function(){return i.tidy("forward",t)});w(o instanceof pt,function(){return"The result y returned by f() must be a tensor."});var a=function(t,e,n){for(var r={},i={},o=0;o=0;o--)for(a=(p=t[o]).inputs,l=0;l0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[o.id]=null==n?(r=Z(S(t=o.shape),"float32"),pt.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var i=e[r],o=[];if(i.outputs.forEach(function(e){var n=t[e.id];if(null!=n)o.push(n);else{var r=pt.make(e.shape,{values:Q(e.size,e.dtype)},e.dtype);o.push(r)}}),null==i.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+i.name+".");var a=i.gradient(1===i.outputs.length?o[0]:o),s=function(e){if(!(e in a))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(a)+".");var r=n(function(){return a[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+i.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var o=i.inputs[e];if(!E(r.shape,o.shape))throw new Error("Error in gradient for op "+i.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+o.shape+"'");if(null==t[o.id])t[o.id]=r;else{var s=t[o.id];t[o.id]=s.add(r),s.dispose()}};for(var u in i.inputs)s(u)},i=e.length-1;i>=0;i--)r(i)}(s,a,function(t){return i.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===i.state.gradientDepth&&(i.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),i.state.activeTape=null),{value:o,grads:u}})},t.prototype.customGrad=function(t){var e=this;return w(G(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],i=0;in||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function ne(t,e){return de(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function re(t,e,n,r,i,o,a,s){var u=t.getAttribLocation(n,r);return-1!==u&&(zt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,i)}),zt(t,e,function(){return t.vertexAttribPointer(u,o,t.FLOAT,!1,a,s)}),zt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ie(t,e,n,r){he(t,r),zt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function oe(t,e,n,r){return de(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function ae(t,e,n){return t.getUniformLocation(e,n)}function se(t,e,n,r,i,o){zt(t,e,function(){return ie(t,e,r,o)}),zt(t,e,function(){return t.uniform1i(i,o)})}function ue(t,e,n,r){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),zt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function ce(t,e,n){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),zt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function le(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+fe(t,e))}function fe(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function de(t,e,n,r){var i=zt(t,e,function(){return n()});if(null==i)throw new Error(r);return i}function he(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function pe(t,e){return void 0===e&&(e=2),S(t.slice(0,t.length-e))}function me(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function ge(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[pe(t)].concat(me(t))),e}function ve(t,e){var n;void 0===e&&(e=!1);var r=h.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?b(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var i=D(t);t=i.newShape}var o=S(t);if(t.length<=1&&o<=r)return[1,o];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var a=pe(t),s=2,u=2;return t.length&&(s=(n=me(t))[0],u=n[1]),C(o=a*(s/2)*(u/2)).map(function(t){return 2*t})}return C(o)}function be(t){return t%2==0}function ye(t,e){if(E(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(be(n)&&be(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&be(t[0])&&be(e[0])}function we(t){if(null==$t){var e=Pt(t);$t=e.getParameter(e.MAX_TEXTURE_SIZE)}return $t}function xe(t){if(null==Gt){var e=Pt(t);Gt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Gt)}function _e(t){if(0===t)return 0;var e=Pt(t);return ke(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:ke(e,"EXT_disjoint_timer_query")?1:0}function ke(t,e){return null!=t.getExtension(e)}function Se(t){try{if(null!=Pt(t))return!0}catch(t){return!1}return!1}function Ee(t){if(0===t)return!1;var e=Pt(t);if(1===t){if(!ke(e,"OES_texture_float"))return!1}else if(!ke(e,"EXT_color_buffer_float"))return!1;return Ae(e,t)}function Oe(t){if(0===t)return!1;var e=Pt(t);if(1===t){if(!ke(e,"OES_texture_float"))return!1;if(!ke(e,"WEBGL_color_buffer_float"))return!1}else if(!ke(e,"EXT_color_buffer_float"))return!1;return Ae(e,t)}function Ae(t,e){var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var i=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,i,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(n),o}function Ce(t){return 2===t&&null!=Pt(t).fenceSync}var Me=Object.freeze({callAndCheck:zt,canBeRepresented:Ut,getWebGLErrorMessage:Wt,getExtensionOrThrow:qt,createVertexShader:Vt,createFragmentShader:Ht,createProgram:Xt,linkProgram:Yt,validateProgram:Jt,createStaticVertexBuffer:Zt,createStaticIndexBuffer:Qt,getNumChannels:function(){return 2===h.getNumber("WEBGL_VERSION")?1:4},createTexture:te,validateTextureSize:ee,createFramebuffer:ne,bindVertexBufferToProgramAttribute:re,bindTextureUnit:ie,unbindTextureUnit:function(t,e,n){he(t,n),zt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:oe,getProgramUniformLocation:ae,bindTextureToProgramUniformSampler:se,bindCanvasToFramebuffer:function(t,e){zt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),zt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),zt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:ue,unbindColorTextureFromFramebuffer:ce,validateFramebuffer:le,getFramebufferErrorMessage:fe,getBatchDim:pe,getRowsCols:me,getShapeAs3D:ge,getTextureShapeFromLogicalShape:ve,isReshapeFree:ye,get MAX_TEXTURE_SIZE(){return $t},get MAX_TEXTURES_IN_SHADER(){return Gt},getWebGLMaxTextureSize:we,getMaxTexturesInShader:xe,getWebGLDisjointQueryTimerVersion:_e,isWebGLVersionEnabled:Se,isRenderToFloatTextureEnabled:Ee,isDownloadFloatTextureEnabled:Oe,isWebGLFenceEnabled:Ce});function Ne(){h.set("PROD",!0)}function Te(){h.set("DEBUG",!0)}function Ie(){h.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function De(t){h.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function je(){It.disposeVariables()}function Re(){return It.memory()}function Fe(t){return It.profile(t)}function Pe(t,e){return It.tidy(t,e)}function ze(t){At(t).forEach(function(t){return t.dispose()})}function Le(t){return It.keep(t)}function Be(t){return It.time(t)}function Ue(t){return It.setBackend(t)}function We(){return It.ready()}function qe(){return It.backendName}function Ve(t){It.removeBackend(t)}function He(t){return It.findBackend(t)}function $e(t){return It.findBackendFactory(t)}function Ge(t,e,n){return void 0===n&&(n=1),It.registerBackend(t,e,n)}function Ke(){return It.backend}function Xe(t,e){h.setPlatform(t,e)}function Ye(){for(var t=[],e=0;e0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),w(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),o=0;o=0&&(i=r),Ze(r,i,e,n),null==t||!B(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var o=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+o+"'")}var a=Je(t);B(t)||Array.isArray(t)||(t=[t]);var s="string"!==i?Y(t,i,h.getBool("DEBUG")):k(t);return pt.make(a,{values:s},i)}function tn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Qe(t,e+"["+r+"]",n)},r)}function en(t,e){for(var n=0;n=0&&e0}),h.registerFlag("WEBGL_VERSION",function(){return Se(2)?2:Se(1)?1:0}),h.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===h.get("WEBGL_VERSION")}),h.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),h.registerFlag("WEBGL_PACK",function(){return h.getBool("HAS_WEBGL")}),h.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_PACK_CLIP",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),h.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_PACK_REDUCE",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_LAZILY_UNPACK",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_CONV_IM2COL",function(){return h.getBool("WEBGL_PACK")}),h.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return we(h.getNumber("WEBGL_VERSION"))}),h.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return xe(h.getNumber("WEBGL_VERSION"))}),h.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=h.getNumber("WEBGL_VERSION");return 0===t?0:_e(t)}),h.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t}),h.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Ee(h.getNumber("WEBGL_VERSION"))}),h.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Oe(h.getNumber("WEBGL_VERSION"))}),h.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Ce(h.getNumber("WEBGL_VERSION"))}),h.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return h.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),ht=De;var hn=dn({complex_:function(t,e){var n=Qe(t,"real","complex"),r=Qe(e,"imag","complex");return x(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),It.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),pn=dn({real_:function(t){var e=Qe(t,"input","real");return It.runKernel(function(t){return t.real(e)},{$input:e})}}),mn=dn({imag_:function(t){var e=Qe(t,"input","imag");return It.runKernel(function(t){return t.imag(e)},{$input:e})}});function gn(t,e,n){return vn(t,e,Je(t),n)}function vn(t,e,n,r){if(null==r&&(r=$(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!B(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){et(e);var i=S(e),o=S(n);w(i===o,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+i+" values but has "+o});for(var a=0;a1)return On([0],r);var i=Q(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return"Pass at least one tensor to concat"});var n=tn(t,"tensors","concat");e=I(e,n[0].shape)[0];var r=fn(n.map(function(t){return t.shape}),e);if(0===S(r))return gn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});ln(i,e);var o=n;return It.runKernel(function(t){return t.concat(n,e)},o,function(t){var n=i.map(function(t){return t[e]});return Pn(t,n,e).map(function(t){return function(){return t}})})}}),Dn=dn({concat1d_:function(t){return In(t,0)}}),jn=dn({concat2d_:function(t,e){return In(t,e)}}),Rn=dn({concat3d_:function(t,e){return In(t,e)}}),Fn=dn({concat4d_:function(t,e){return In(t,e)}}),Pn=dn({split_:function(t,e,n){void 0===n&&(n=0);var r,i=Qe(t,"x","split");return n=I(n,i.shape)[0],"number"==typeof e?(w(i.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(i.shape[n]/e)):(w(i.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),It.runKernel(function(t){return t.split(i,r,n)},{$x:i},function(t){return{$x:function(){return In(t,n)}}})}});function zn(t,e){return t(e={exports:{}},e.exports),e.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r||"undefined"!=typeof self&&self;var Ln=zn(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),Bn=zn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Un=zn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Wn=zn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),qn=zn(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,o=-32;o>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Vn=zn(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Hn=zn(function(t){!function(e,r){var i,o=this,a=256,s=6,u="random",c=r.pow(a,s),l=r.pow(2,52),f=2*l,d=a-1;function h(t,n,d){var h=[],b=g(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,v(e)]:null==t?function(){try{var t;return i&&(t=i.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),v(t)}catch(t){var n=o.navigator,r=n&&n.plugins;return[+new Date,o,r,o.screen,v(e)]}}():t,3),h),y=new p(h),w=function(){for(var t=y.g(s),e=c,n=0;t=f;)t/=2,e/=2,n>>>=1;return(t+n)/e};return w.int32=function(){return 0|y.g(4)},w.quick=function(){return y.g(4)/4294967296},w.double=w,g(v(y.S),e),(n.pass||d||function(t,e,n,i){return i&&(i.S&&m(i,y),t.state=function(){return m(y,{})}),n?(r[u]=t,e):t})(w,b,"global"in n?n.global:this==r,n.state)}function p(t){var e,n=t.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Kn=function(){function t(t,e,n,r){void 0===t&&(t=0),void 0===e&&(e=1);var i=this;if(this.canReturnFloat=function(){return null==i.dtype||"float32"===i.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=$n(r)}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}();function Xn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",et(t),new lt(t,e,n)}function Yn(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Jn=dn({batchToSpaceND_:function(t,e,n){var r=Qe(t,"x","batchToSpaceND"),i=e.reduce(function(t,e){return t*e});return w(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),w(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),w(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),It.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Zn=dn({cast_:function(t,e){var n=Qe(t,"x","cast");if(!z(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return It.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Qn=dn({clone_:function(t){var e=Qe(t,"x","clone",null);return It.runKernel(function(t){return pt.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),tr=dn({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=Qe(t,"x","cumsum"),o=sn([e|=0],i.rank),a=i;null!=o&&(a=i.transpose(o));var s=cn(1,i.rank)[0],u=It.runKernel(function(t){return t.cumsum(a,s,n,r)},{permutedX:a},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=o&&(u=u.transpose(o)),u}}),er=dn({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Qe(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return w(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),w(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape}),w(a%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape}),It.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),nr=dn({expandDims_:function(t,e){void 0===e&&(e=0);var n=Qe(t,"x","expandDims",null);w(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(w(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),pr(n,r)}}),rr=dn({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=Xn([t,e],r),o=t<=e?t:e,a=0;a2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?i.as2D(1,-1):i,u=It.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===a?u.as1D():u}}),or=dn({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var i=Qe(t,"indices","oneHot","int32"),o=i.shape.concat([e]);return i=i.flatten(),It.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return On(i.shape,"float32")}}}).reshape(o)}}),ar=dn({pad_:function(t,e,n){void 0===n&&(n=0);var r=Qe(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return It.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),sr=dn({pad1d_:function(t,e,n){return void 0===n&&(n=0),w(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),ar(t,[e],n)}}),ur=dn({pad2d_:function(t,e,n){return void 0===n&&(n=0),w(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ar(t,e,n)}}),cr=dn({pad3d_:function(t,e,n){return void 0===n&&(n=0),w(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ar(t,e,n)}}),lr=dn({pad4d_:function(t,e,n){return void 0===n&&(n=0),w(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),ar(t,e,n)}}),fr=dn({rand_:function(t,e,n){var r=S(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var o=0;o=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),w(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),w(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),It.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),gr=dn({squeeze_:function(t,e){var n=Qe(t,"x","squeeze");return pr(n,D(n.shape,e).newShape)}}),vr=dn({stack_:function(t,e){void 0===e&&(e=0);var n=tn(t,"tensors","stack");if(w(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,i=n[0].shape,o=n[0].dtype;w(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){x(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){w(o===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=n.map(function(t){return t.expandDims(e)});return In(a,e)}}),br=dn({tile_:function(t,e){var n=Qe(t,"x","tile",null);return w(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),It.runKernel(function(t,r){var i=t.tile(n,e);return r([n]),i},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=Tn(r);if(1===r.rank)for(var i=0;i=-n.shape.length&&e=2*e+1||i%2==1?a.push(i):o.push(i);r.push.apply(r,o),r.push(0),r.push.apply(r,a)}return r}function Sr(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var o=1;ot.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],i=1,o=0;o1?e.shape[e.rank-1]:1,i=n.length,o=1,a=r;a0?o>=l[e]:o<=l[e]);o+=i)n+=1;return n}),[c,h,f]}function Ir(t,e,n,r,i){var o=e[i],a=n[i]||1;(t&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[i];return o<0&&(o+=s),v(0,o,s-1)}function Dr(t,e,n,r,i){var o=e[i],a=n[i]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[i];return o<0&&(o+=s),a>0?v(0,o,s):v(-1,o,s-1)}function jr(t,e,n){for(var r=n.length,i=0;i1){r=i;break}for(i=r+1;i0||n[i]!==t[i])return!1;return!0}function Rr(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+o+" variables is trainable."});var a=It.gradients(t,e,null,!0),s=a.value,u=a.grads;w(u.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),w(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return e.forEach(function(t,e){null!=u[e]&&(c[t.name]=u[e])}),null!=i&&i.forEach(function(t){return c[t.name]=null}),{value:s,grads:c}}function Ur(t){return It.customGrad(t)}function Wr(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var qr=dn({softmax_:function(t,e){void 0===e&&(e=-1);var n=Qe(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Ur(function(t,n){var r=t.logSumExp([e],!0),i=t.toFloat().sub(r).exp();return n([i]),{value:i,gradFunc:function(t,n){var r=n[0],i=t.mul(r);return i.sub(i.sum([e],!0).mul(r))}}})(n)}}),Vr=dn({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Qe(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Ur(function(t,n){var r=t.max(e,!0),i=t.sub(r),o=i.toFloat().sub(i.exp().sum(e,!0).log());return n([o]),{value:o,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),Hr=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),$r=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s,u){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.isNaN=function(t){throw new Error("Not yet implemented")},t.prototype.isInf=function(t){throw new Error("Not yet implemented")},t.prototype.isFinite=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function Gr(t,e){for(var n=t.length,r=[],i=0;i1&&1===a&&r.unshift(o)}return r}function Kr(t,e){for(var n=[],r=0;r1)&&n.unshift(o)}return n}function Xr(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;ii}).sort(function(t,e){return e.score-t.score}),a=[],s=0;s=0;--d)if(mi(t,l,a[d])>=r){f=!0;break}if(!f&&(a.push(l),a.length>=n))break}return yn(a,"int32")}function mi(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(i[0],i[2]),l=Math.min(i[1],i[3]),f=Math.max(i[0],i[2]),d=Math.max(i[1],i[3]),h=(s-o)*(u-a),p=(f-c)*(d-l);if(h<=0||p<=0)return 0;var m=Math.max(o,c),g=Math.max(a,l),v=Math.min(s,f),b=Math.min(u,d),y=Math.max(v-m,0)*Math.max(b-g,0);return y/(h+p-y)}function gi(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var o=t.slice(r,i);return r[n]+=e,o})}function vi(t,e){for(var n=new Array(t.rank),r=0;r= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var a=xi("coords",i);o+="\n bool nextRowOutOfBounds =\n ("+a[i-2]+" + 1) >= "+this.outputShape[i-2]+";\n bool nextColOutOfBounds =\n ("+a[i-1]+" + 1) >= "+this.outputShape[i-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+o+"\n\n setOutput(result);\n }\n "},Ui=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, min, max));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Wi=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(min), vec4(max)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}();function qi(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var Vi,Hi,$i=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),Gi=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},Ki=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}();function Xi(t,e){return[e,t]}function Yi(t){var e=S(t);return C(Math.ceil(e/4))}function Ji(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Zi(t,e){var n=_i();return Vt(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Qi(t,e){return Zt(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function to(t,e){return Qt(t,e,new Uint16Array([0,1,2,2,1,3]))}function eo(t,e){var n,r,i,o,a,s,u,c,l=t;return 2===h.getNumber("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,i=l.RGBA16F,o=l.RGBA32F,a=l.RED,s=4,u=1,c=l.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,i=t.RGBA,o=l.RGBA,a=t.RGBA,s=4,u=4,c=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:c}}function no(t,e,n,r,i,o,a){ee(n,r);var s=te(t,e),u=t.TEXTURE_2D;return zt(t,e,function(){return t.bindTexture(u,s)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),zt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),zt(t,e,function(){return t.texImage2D(u,0,i,n,r,0,o,a,null)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function ro(t,e,n,r,i){var o=Xi(n,r);return no(t,e,o[0],o[1],i.internalFormatFloat,i.textureFormatFloat,t.FLOAT)}function io(t,e,n,r,i){var o=Xi(n,r);return no(t,e,o[0],o[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function oo(t,e,n,r,i){var o=Xi(n,r);return no(t,e,o[0],o[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ao(t,e,n,r,i){var o=Ji(n,r);return no(t,e,o[0],o[1],i.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function so(t,e,n,r,i){var o=Ji(n,r);return no(t,e,o[0],o[1],i.internalFormatPackedHalfFloat,t.RGBA,i.textureTypeHalfFloat)}function uo(t,e,n,r){return zt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),re(t,e,n,"clipSpacePos",r,3,20,0)&&re(t,e,n,"uv",r,2,20,12)}function co(t,e,n,r,i,o,a){var s,u,c;zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),o instanceof Uint8Array?(s=new Uint8Array(r*i*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*i*4),u=t.FLOAT,c=a.internalFormatPackedFloat),s.set(o),zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,i,0,t.RGBA,u,s)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function lo(t,e,n,r){zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):zt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),zt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function fo(t,e,n,r,i){var o=t.createBuffer();zt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,o)});var a=16*n*r;return zt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,a,t.STREAM_READ)}),zt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),zt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),o}function ho(t,e,n){var r=t,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function po(t,e,n,r,i){var o=Xi(n,r),a=o[0],s=o[1],u=new Uint8Array(n*r*4);return zt(t,e,function(){return t.readPixels(0,0,a,s,i.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function mo(t,e,n,r,i,o,a,s){var u=t,c=new Float32Array(function(t,e){var n=Ji(o,a);return n[0]*n[1]*4}());return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function go(t,e,n,r){var i=new Float32Array(n*r*4);return zt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,i)}),i}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Vi||(Vi={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Hi||(Hi={}));var vo=Object.freeze({createVertexShader:Zi,createVertexBuffer:Qi,createIndexBuffer:to,getTextureConfig:eo,createFloat32MatrixTexture:ro,createFloat16MatrixTexture:io,createUnsignedBytesMatrixTexture:oo,createPackedMatrixTexture:ao,createFloat16PackedMatrixTexture:so,bindVertexProgramAttributeStreams:uo,uploadDenseMatrixToTexture:co,uploadPixelDataToTexture:lo,createBufferFromOutputTexture:fo,downloadFloat32MatrixFromBuffer:ho,downloadByteEncodedFloatMatrixFromOutputTexture:po,downloadPackedMatrixFromBuffer:mo,downloadMatrixFromPackedOutputTexture:go}),bo=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=h.getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ft(e,t)):this.gl=Pt(e),1===h.getNumber("WEBGL_VERSION")?(this.textureFloatExtension=qt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),h.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=qt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=qt(this.gl,this.debug,"EXT_color_buffer_float"),this.vertexBuffer=Qi(this.gl,this.debug),this.indexBuffer=to(this.gl,this.debug),this.framebuffer=ne(this.gl,this.debug),this.textureConfig=eo(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return h.getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;zt(e,this.debug,function(){return e.finish()}),zt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),zt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),zt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),zt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),zt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),ro(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),io(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),oo(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),lo(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),co(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),so(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ao(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(ce(this.gl,this.debug,this.framebuffer),this.outputTexture=null),zt(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return po(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,i,o){return mo(this.gl,t,0,0,0,i,o,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return ho(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=fo(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(h.getBool("WEBGL_FENCE_API_ENABLED")){var i=t,o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=i.clientWaitSync(o,0,0);return t===i.ALREADY_SIGNALED||t===i.CONDITION_SATISFIED},e=o}else h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return go(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=Ht(e,this.debug,t),r=Zi(e,this.debug),i=Xt(e,this.debug);return zt(e,this.debug,function(){return e.attachShader(i,r)}),zt(e,this.debug,function(){return e.attachShader(i,n)}),Yt(e,this.debug,i),this.debug&&Jt(e,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=uo(e,this.debug,this.program,this.vertexBuffer)),i},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&zt(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Jt(this.gl,this.debug,this.program),zt(this.gl,this.debug,function(){return e.gl.useProgram(t)})},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?oe(this.gl,this.debug,t,e):ae(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),zt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),se(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Ji(e,n),i=r[0],o=r[1];this.setOutputMatrixTextureDriver(t,i,o)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&Jt(this.gl,this.debug,this.program),le(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),zt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),zt(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=qt(this.gl,this.debug,2===h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},t.prototype.endQuery=function(){if(2!==h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return c(this,void 0,void 0,function(){var e=this;return l(this,function(n){switch(n.label){case 0:return[4,N(function(){return e.disposed||e.isQueryAvailable(t,h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||N(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ue(this.gl,this.debug,t,this.framebuffer),this.debug&&le(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ue(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&le(this.gl)):ce(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;ue(r,this.debug,t,this.framebuffer),this.debug&&le(r),this.outputTexture=t,zt(r,this.debug,function(){return r.viewport(0,0,e,n)}),zt(r,this.debug,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),zt(this.gl,this.debug,function(){return i.gl.scissor(t,e,n,r)})},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function yo(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,i=e[n],o=i.shape;if(!E(r,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+o+" must match");if(!t.isUniform||!i.isUniform){var a=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!E(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}})}var wo=function(t,e,n,r,i,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===o&&(o=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var a=n?t[1]:t[2],s=Math.ceil(a/2),u=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",l=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",h="";o&&(d="vec4 activation(vec4 x) {\n "+o+"\n }",h="result = activation(result);");var p=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),this.userCode="\n "+d+"\n\n const float sharedDimension = "+s+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+s+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n result += ("+l[0]+" * "+f[0]+") + ("+l[1]+" * "+f[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+p+"\n\n "+h+"\n\n setOutput(result);\n }\n "},xo=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),_o=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;var d="avg"===e,h="0.0";if(d||(h="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+l+", "+f+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+c+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var p=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(p="avgValue / count");var m=4*Math.floor(r/4),g=r%4,v="\n if ("+d+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+l+", "+f+");\n const float initializationValue = "+h+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+h+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+p+");\n }\n "}},ko=function(t,e,n,r,i,o,a){void 0===a&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=Ii(i.length),u=Ii(o.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",f="";1===r?f="i":2===r&&(f="i, coords[1]");var d="getUpdates("+f+")",h=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+l+");\n flattenedIndex += index * "+h+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+d+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},So=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Ii(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return Eo.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return"sourceLoc."+Eo[e]+" = start["+e+"] + coords."+Eo[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+i+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Eo=["x","y","z","w","u","v"],Oo=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Ii(this.rank),n=xi("coords",this.rank),r=xi("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",o="getChannel(getSource("+r.join()+"), "+i+")",a="\n result.x = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+o+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+o+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+o+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+" \n vec4 result = vec4(0.);\n "+a+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ao=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,i=Co(e,n),o=Mo(t,i,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[o].shift();return this.usedTextures[o].push(a),a}return this.numUsedTextures++,this.log(),i===Hi.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Hi.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Hi.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Hi.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Hi.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var i=Mo(e,Co(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[i],a=o.indexOf(t);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Co(t,e){if(t===Vi.UPLOAD)return Hi.PACKED_2X2_FLOAT32;if(t===Vi.RENDER||null==t)return e?h.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Hi.PACKED_2X2_FLOAT32:Hi.PACKED_2X2_FLOAT16:h.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Hi.UNPACKED_FLOAT32:Hi.UNPACKED_FLOAT16;if(t===Vi.DOWNLOAD||t===Vi.PIXELS)return Hi.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Mo(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var No=function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n float unaryOperation(float x) {\n "+e+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n "},To="if (isnan(x)) return x;",Io=To+"\n return (x < 0.0) ? 0.0 : x;\n",Do="return exp(x);",jo="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Ro=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "},Fo={},Po=600,zo=function(){function t(t){if(this.gpgpu=t,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.disposed=!1,!h.getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==t){var e=Pt(h.getNumber("WEBGL_VERSION"));this.binaryCache=(n=h.getNumber("WEBGL_VERSION"))in Fo?Fo[n]:(Fo[n]={},Fo[n]),this.gpgpu=new bo(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;var n;this.textureManager=new Ao(this.gpgpu),this.numMBBeforeWarning=null==h.global.screen?1024:h.global.screen.height*h.global.screen.width*window.devicePixelRatio*Po/1024/1024,this.texData=new Hr(this,It)}return t.prototype.register=function(t,e,n){if(this.texData.has(t))throw new Error("Data buffer is already registered");this.texData.set(t,{shape:e,dtype:n})},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=[t.height,t.width],r=[t.height,t.width,e];if(h.getBool("IS_BROWSER")){if(!(t instanceof HTMLVideoElement||t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof ImageData||t.data instanceof Uint8Array))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(t instanceof HTMLVideoElement){if(null==this.fromPixels2DContext){if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.browser.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixels2DContext=document.createElement("canvas").getContext("2d")}this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),t=this.fromPixels2DContext.canvas}}var i,o,a=this.makeTensorHandle(n,"int32");if(this.texData.get(a.dataId).usage=Vi.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(a.dataId),t),h.getBool("WEBGL_PACK")){i=new function(t){this.variableNames=["A"];var e=_i(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "}(r);var s=this.makePackedTensor(i.outputShape,a.dtype);o=this.compileAndRun(i,[a],s)}else i=new function(t){this.variableNames=["A"];var e=_i(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "}(r),o=this.compileAndRun(i,[a]);return this.disposeData(a.dataId),o},t.prototype.makeTensorHandle=function(t,e){var n={};return this.register(n,t,e),{dataId:n,shape:t,dtype:e}},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendWebGL.write(): values can not be null");if(h.getBool("DEBUG"))for(var n=0;n0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},t.prototype.endTimer=function(t){return h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=performance.now(),t)},t.prototype.getQueryTime=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){return h.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}},t.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,i=e.texShape,o=e.usage,a=e.isPacked,s=e.slice,u=s&&s.origDataId||t,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,o,a)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getCPUBackend=function(){return h.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=It.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=xi("rc",n),i=r[n-1]+" + 1 < "+this.outputShape[n-1],o=r[n-2]+" + 1 < "+this.outputShape[n-2],a=Ii(n);function s(n){var r=t.map(function(r,i){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(i,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+i+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+a+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+s(r.slice())+";\n if("+i+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+o+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+i+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "}(t.shape,e):new function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),i=Ii(n);this.userCode="\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "}(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.concat=function(t,e){if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>h.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),i=this.concat(t.slice(n),e);return this.concat([r,i],e)}if(h.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var o=new function(t,e){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=fn(t,e);var n=this.outputShape,r=n.length,i=Ii(r),o=xi("coords",r),a=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===o?t:t.as3D(s,a,1),c=1===o?2:1,l=1===o?e.as3D(s,1,a):e;return this.multiply(u,l).sum(c,!0)}var f=kt(t.dtype,e.dtype),d=new wo(t.shape,[s,i,o],n,r),h=this.makePackedTensor(d.outputShape,f);return this.compileAndRun(d,[t,e],h)},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){var a=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],c=kt(t.dtype,e.dtype),l=new wo(t.shape,[u,a,s],n,r,!!i,o?function(t,e){if(void 0===e&&(e=!1),"linear"===t)return"return x;";if("relu"===t)return e?jo:Io;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}(o,!0):null),f=this.makePackedTensor(l.outputShape,c),d=[t,e];return i&&d.push(i),this.compileAndRun(l,d,f)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),i=new Ri("return areal * breal - aimag * bimag;",t.shape,e.shape),o=new Ri("return areal * bimag + aimag * breal;",t.shape,e.shape),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],s=this.compileAndRun(i,a),u=this.compileAndRun(o,a),c=this.complex(s,u);return s.dispose(),u.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,zi,t.dtype);var l=new Li(zi,t.shape,e.shape),f=this.makeOutputArray(l.outputShape,t.dtype);return this.compileAndRun(l,[t,e],f)},t.prototype.batchNormalization=function(t,e,n,r,i,o){var a=[t,e,n],s=null;null!=o&&(s=o.shape,a.push(o));var u=null;if(null!=i&&(u=i.shape,a.push(i)),h.getBool("WEBGL_PACK_NORMALIZATION")){var c=new function(t,e,n,r,i,o){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Xr(t,e),Xr(t,n);var a="vec4(0.0)";null!=r&&(Xr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(Xr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+a+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "}(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,a)}var l=new function(t,e,n,r,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],Xr(t,e),Xr(t,n);var a="0.0";null!=r&&(Xr(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=i&&(Xr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+a+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "}(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,a)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){var o=h.getBool("WEBGL_PACK_NORMALIZATION")?new function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var o,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+a+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+a+"; j <= "+a+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+o+";\n setOutput(result);\n }\n "}(t.shape,e,n,r,i):new function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var o,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+a+"; j <= "+a+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+o+";\n setOutput(val);\n }\n "}(t.shape,e,n,r,i);return this.compileAndRun(o,[t])},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){var s=new function(t,e,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "}(e.shape,r,i,o,a);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){if("string"===t.dtype)return vi(Xn(t.shape,t.dtype,this.readSync(t.dataId)),e);var n=new function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="",p=0,m=1===r?2:4;p= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=h.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;for(var n=new Array(t.length),r=0;r6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=Ii(this.rank),o=wi("rc",this.rank),a=new Array(this.rank);for(r=0;r6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],o=0;o 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=_r(t.shape,e,r),o=kr(i.length,e.length),a=Sr(t.shape,e,r),s=Er(n,e.length),u=Or(a,n,e.length);return t.reshape(i).transpose(o).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){w(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var o=1+e.length;o= 1.0 && floatedReducedAllValue >= 1.0);\n ",d="bvec4"):"any"===e&&(a="0.0",f="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",d="bvec4");var h="";i%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+h+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+a+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+c+"; i += 4) {\n int inIdx = inOffset + i;\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+f+"\n }\n\n int inIdx = inOffset + "+c+";\n if ("+(1===l)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===l)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===l)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+f+"\n }\n setOutput("+u+");\n }\n "}({windowSize:Mr(i),inSize:i,batchSize:r},e),a=o.outputShape,s=a[0],u=a[1],c=this.makeOutputArray([s,u],n);return this.compileAndRun(o,[t],c),1===c.shape[1]?c:this.reduce(c,e,n)},t.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],i=t.shape[1];null!=n&&(r=n.shape[0],i=n.shape[1]);var o=new function(t,e,n){this.variableNames=["A"];var r=t.windowSize,i=t.batchSize,o=t.inSize,a=Math.ceil(o/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,a];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "}({windowSize:Mr(i),inSize:i,batchSize:r},e,null==n),a=o.outputShape,s=a[0],u=a[1],c=this.makeOutputArray([s,u],"int32"),l=[t];return null!=n&&l.push(n),this.compileAndRun(o,l,c),1===c.shape[1]?c:this.argReduce(t,e,c)},t.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,i=new function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,w(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],o=Math.ceil(i/e);this.outputShape=t.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,c=u.length,l=Ii(c),f=xi("coords",c);if(1===o){var d=Ii(s=c+1);a="\n "+d+" sourceLocR = "+d+"("+f.join()+", 0);\n ++"+f[c-1]+";\n "+d+" sourceLocG = "+d+"("+f.join()+", 0);\n ++"+f[c-2]+";\n "+d+" sourceLocA = "+d+"("+f.join()+", 0);\n --"+f[c-1]+";\n "+d+" sourceLocB = "+d+"("+f.join()+", 0);\n --"+f[c-2]+";"}else s=c,a="\n "+l+" sourceLocR = coords;\n ++"+f[c-1]+";\n "+l+" sourceLocG = coords;\n ++"+f[c-2]+";\n "+l+" sourceLocA = coords;\n --"+f[c-1]+";\n "+l+" sourceLocB = coords;\n --"+f[c-2]+";";var h=["x","y","z","w","u","v"].slice(0,s),p="."+h[s-1],m=h.map(function(t){return"int "+t}),g=xi("sourceLocR",s-1).concat("inIdx.r"),v=xi("sourceLocG",s-1).concat("inIdx.g"),b=xi("sourceLocB",s-1).concat("inIdx.b"),y=xi("sourceLocA",s-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",_=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+b.join()+"),\n getBestIndicesAChannel("+y.join()+")));",k="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+b.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+y.join()+") : 0.)",S=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+h.join()+"),\n vec2("+h.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+h.join()+"),\n vec2("+h.slice(-2).join()+"));\n }\n "+S+"\n void main() {\n "+l+" coords = getOutputCoords();\n bool hasNextCol = "+f[c-1]+" < "+(u[c-1]-1)+";\n bool hasNextRow = "+f[c-2]+" < "+(u[c-2]-1)+";\n "+a+"\n ivec4 srcIdx = ivec4(sourceLocR"+p+", sourceLocG"+p+",\n sourceLocB"+p+", sourceLocA"+p+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+k+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+_+"\n vec4 candidate = "+k+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+x+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "}(r,Mr(r[r.length-1]),e,null==n),o=this.makePackedTensor(i.outputShape,"int32"),a=null==n?[t]:[t,n];return this.compileAndRun(i,a,o),o.rank===t.rank?this.argReducePacked(t,e,o):o},t.prototype.sum=function(t,e){an("sum",e,t.rank);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i),a=St(t.dtype);return this.reduce(o,"sum",a).reshape(r)},t.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i),a=St(t.dtype);return this.reduce(o,"prod",a).reshape(r)},t.prototype.unsortedSegmentSum=function(t,e,n){var r=0,i=sn([r],t.rank),o=t;null!=i&&(o=t.transpose(i),r=cn(1,t.rank)[0]);var a=function(t,e,n){for(var r=[],i=t.length,o=0;oe||n===t?r=!0:n=K(t,n+1);return n}(a,i),u=new function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,o=t.numSegments,a=o*Math.ceil(i/n);this.outputShape=[r,a];var s=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ",l="";i%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var f="";i%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+l+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+f+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+c+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+c+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+c+"\n }\n setOutput(sumValue);\n }\n "}({windowSize:s,inSize:a,batchSize:o,numSegments:i},e),c=u.outputShape,l=c[0],f=c[1],d=this.makeOutputArray([l,f],r);return this.compileAndRun(u,[t,n],d),d.shape[1]===i?d:(n=Mn(0,i).tile([a/s]),this.segOpCompute(d,e,n,r,i))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(an("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!h.getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var i=rn(t.shape,r),o=i[0],a=S(i[1]),s=t.as2D(-1,a);return this.argReduce(s,n).reshape(o)}return this.argReducePacked(t,n)},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var i=new function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],o=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Ii(r)+" coords = getOutputCoords();\n int end = "+qi(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+qi(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}(t.shape,n,r);return this.compileAndRun(i,[t])},t.prototype.equal=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Li("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.notEqual=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Li("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Li("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.lessEqual=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Li("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Li("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Li("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalNot=function(t){var e=new No(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Li("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalOr=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new Li("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.select=function(t,e,n){var r=new function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "}(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,kt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},t.prototype.where=function(t){Ye("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return yi(t.shape,e)},t.prototype.topk=function(t,e,n){return bi(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){an("min",e,t.rank);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.mod=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);an("max",e,t.rank);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i);return this.reduce(o,"max",o.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.all=function(t,e){an("all",e,t.rank);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(r)},t.prototype.any=function(t,e){an("any",e,t.rank);var n=rn(t.shape,e),r=n[0],i=S(n[1]),o=t.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("return (a - b) * (a - b);",t.shape,e.shape):new Li("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(b.x == 0.0) {\n result.x = NAN;\n } else if(a.x == b.x) {\n result.x = 1.;\n }\n if(b.y == 0.0) {\n result.y = NAN;\n } else if(a.y == b.y) {\n result.y = 1.;\n }\n if(b.z == 0.0) {\n result.z = NAN;\n } else if(a.z == b.z) {\n result.z = 1.;\n }\n if(b.w == 0.0) {\n result.w = NAN;\n } else if(a.w == b.w) {\n result.w = 1.;\n }\n \n return result;\n","float32",!0);var n=new Li("\nif (b == 0.0) {\n return NAN;\n} \nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r)},t.prototype.floorDiv=function(t,e){if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new Li("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r)},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Fi);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=kt(t.dtype,e.dtype);if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Fi,n);var r=new Li(Fi,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.packedBinaryOp=function(t,e,n,r,i){void 0===i&&(i=!1);var o=new Bi(n,t.shape,e.shape,i),a=this.makePackedTensor(o.outputShape,r);return this.compileAndRun(o,[t,e],a)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),o=this.texData.get(e.dataId),a=[[i.complexTensors.real,o.complexTensors.real],[i.complexTensors.imag,o.complexTensors.imag]].map(function(i){var o=i[0],a=i[1],s=r.makeComplexComponentTensorHandle(t,o),u=r.makeComplexComponentTensorHandle(e,a),c=new Li(n,t.shape,e.shape),l=r.makeOutputArray(c.outputShape,kt(o.dtype,a.dtype));return r.compileAndRun(c,[s,u],l)}),s=a[0],u=a[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>h.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var i=t.map(function(t){return t.dtype}).reduce(function(t,e){return kt(t,e)}),o=t.map(function(t){return t.shape}),a=h.getBool("WEBGL_PACK"),s=a?new function(t,e){this.outputShape=[],this.usesPackedTextures=!0,this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")});var r=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n vec4 result = "+r+";\n setOutput(result);\n }\n "}(t[0].shape,o):new function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();")});var r=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n float result = "+r+";\n setOutput(result);\n }\n "}(t[0].shape,o),u=a?this.makePackedTensor(s.outputShape,i):this.makeOutputArray(s.outputShape,i);return this.compileAndRun(s,t,u)},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Pi);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=kt(t.dtype,e.dtype);if(h.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Pi,t.dtype);var r=new Li(Pi,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.pow=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new Bi("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),i=kt(t.dtype,e.dtype),o=n?this.makePackedTensor(r.outputShape,i):this.makeOutputArray(r.outputShape,i);return this.compileAndRun(r,[t,e],o)},t.prototype.ceil=function(t){var e=new No(t.shape,"return ceil(x);");return this.compileAndRun(e,[t])},t.prototype.floor=function(t){var e=new No(t.shape,"return floor(x);");return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new No(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},t.prototype.isNaN=function(t){var e=new No(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isInf=function(t){var e=new No(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isFinite=function(t){var e=new No(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.round=function(t){var e=new No(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},t.prototype.exp=function(t){var e;return e=h.getBool("WEBGL_PACK")?new Ro(t.shape,Do):new No(t.shape,Do),this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new No(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e;return e=h.getBool("WEBGL_PACK")?new Ro(t.shape,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n"):new No(t.shape,"if (x < 0.0) return NAN;\n return log(x);"),this.compileAndRun(e,[t])},t.prototype.log1p=function(t){var e=new No(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new No(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new No(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new No(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new No(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=h.getBool("WEBGL_PACK")?new Ro(t.shape,jo):new No(t.shape,Io),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Li("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){var e=new No(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Li("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.selu=function(t){var e=new No(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new No(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},t.prototype.clip=function(t,e,n){var r,i=(r=h.getBool("WEBGL_PACK_CLIP")?new Wi(t.shape):new Ui(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,i)},t.prototype.abs=function(t){var e=new No(t.shape,"return abs(x);");return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(t){var e=new No(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new No(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},t.prototype.sin=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new No(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new No(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new No(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=h.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.sinh=function(t){var e=new No(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.cosh=function(t){var e=new No(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.tanh=function(t){var e=new No(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},t.prototype.asinh=function(t){var e=new No(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},t.prototype.atanh=function(t){var e=new No(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},t.prototype.erf=function(t){var e=new No(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new No(t.shape,function(t){return void 0===t&&(t=0),To+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,i=this.texData.get(t.dataId),o=n.inChannels,a=r[0]*r[1]*r[2],s=n.outChannels,u=(1===a||1===s)&&o>1e3,c=r[2]%2!=0&&!!i.isPacked;if(u||!h.getBool("WEBGL_LAZILY_UNPACK")||!h.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!c){var l=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),f=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(l,f,!1,!1),n.outShape)}var d=pt.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),p=i.shape;i.shape=i.shape.slice(),i.shape[i.shape.length-2]++,w(ye(i.shape,d.shape),function(){return"packed reshape "+i.shape+" to "+d.shape+" isn't free"});var m=this.reshape(e,[1,n.inChannels,n.outChannels]),g=this.batchMatMul(d,m,!1,!1),v=this.texData.get(g.dataId);return w(v.isPacked,function(){return"batchMatMul result is expected to be packed"}),i.shape=p,v.shape=n.outShape,pt.make(n.outShape,{dataId:g.dataId},g.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,i=n.filterHeight,o=n.inChannels,a=n.outWidth,s=n.outHeight,u=r*i*o,c=s*a,l=[u,c],f=t.squeeze([0]),d=e.reshape([1,u,-1]),h=new function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var r=n.filterWidth,i=n.inChannels,o=n.strideWidth,a=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,f=s.left,d=s.top,h=i*r,p=_i();this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n int blockIndex = rc.y + col;\n int pos = rc.x + row;\n\n if(blockIndex >= "+t[1]+" || pos >= "+t[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+a+" - "+d+";\n int d0 = offsetY + "+l+" * (pos / "+h+");\n\n if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+o+". - "+f+".);\n int d1 = offsetX + "+c+" * (int(mod(float(pos), "+h+".) / "+i+".));\n\n if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n vec2 innerDims = vec2(d1, int(mod(float(pos), "+i+".)));\n result[row * 2 + col] = getChannel(getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n\n "+p.output+" = result;\n }\n "}(l,f.shape,n),p=this.compileAndRun(h,[f]).reshape([1,l[0],l[1]]),m=new wo(p.shape,[1,c,n.outChannels],!0,!1);return this.compileAndRun(m,[p,d]).reshape([1,s,a,n.outChannels])},t.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(h.getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,c=4*Math.floor(t.inChannels/4),l=t.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+i+");\n const ivec2 pads = ivec2("+e+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+"; wR++) {\n int xR = xRCorner + wR * "+o+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+c+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===l)+") {\n dotProd +=\n getX(batch, xR, xC, "+c+") *\n getW(wR, wC, "+c+", d2);\n } else if ("+(2===l)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===l)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1),\n getX(batch, xR, xC, "+c+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2),\n getW(wR, wC, "+c+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r;return h.getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.filterHeight,l=t.filterWidth,f=l,d="int xR; int xC; int xCOffset;",h=0;h= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+p+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+h+"C"+p+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+h+"C"+p+" = vec4(previous.zw, xTexelR"+h+"C"+p+".xy);\n } else {\n xR"+h+"C"+p+" = vec4(0, 0, xTexelR"+h+"C"+p+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+h+"C"+p+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+h+"C"+p+" = vec4(0.);\n }\n\n xR"+h+"C"+p+" = xTexelR"+h+"C"+p+";\n ",p+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+(p+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(d+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+p+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+h+"C"+p+" = vec4(0.);\n }\n "),d+="\n xR"+h+"C"+(p+1)+" = vec4(\n xTexelR"+h+"C"+p+".zw, xTexelR"+h+"C"+(p+2)+".xy);\n "):d+="\n xCOffset = xC + "+g+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+(p+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+h+"C"+(p+1)+" = xTexelR"+h+"C"+(p+2)+";\n "}}else p= 0 && xR < "+e+") {\n ",i%2==1?(d+="\n xCOffset = xC + 1 - "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+p+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+h+"C"+p+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+h+"C"+(p+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+h+"C"+(p+2)+" = vec4(0.);\n }\n\n xR"+h+"C"+p+" = vec4(\n xTexelR"+h+"C"+p+".zw, xTexelR"+h+"C"+(p+2)+".zw);\n ",p+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+h+"C"+(p+1)+" = vec4(xTexelR"+h+"C"+(p+2)+".xy, final.xy);\n ")):(d+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+h+"C"+p+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+h+"C"+p+" = vec4(0.);\n }\n\n xCOffset = xC + "+a+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+h+"C"+(p+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+h+"C"+(p+2)+" = vec4(0.);\n }\n\n xR"+h+"C"+p+" = vec4(\n xTexelR"+h+"C"+p+".xy, xTexelR"+h+"C"+(p+2)+".xy);\n ",p+1= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "}(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,f=t.filterHeight,d=t.filterWidth,h=4*Math.floor(t.inChannels/4),p=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+o+", "+a+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+l+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+f+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+c+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===p)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+h+") *\n getW(wF, wR, wC, "+h+", d2);\n } else if ("+(2===p)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===p)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1),\n getX(batch, xF, xR, xC, "+h+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2),\n getW(wF, wR, wC, "+h+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,c=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+c+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,o=t.padInfo.top,a=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+i+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+o+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new _o(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},t.prototype.avgPool=function(t,e){var n=new _o(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var i=new _o(r,"max",!0),o=this.compileAndRun(i,[e]),a=new function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,o=t.effectiveFilterWidth,a=i-1-t.padInfo.top,s=o-1-t.padInfo.left,u=i*o-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}(r),s=this.makeOutputArray(a.outputShape,e.dtype),u=this.compileAndRun(a,[t,o],s);return o.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,f=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\n const float avgMultiplier = float("+f+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},t.prototype.cast=function(t,e){return ai(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,o=0;o1?o-1:o,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+",\n "+u[1]/c[1]+");\n const vec3 inputShapeRC = vec3("+o+".0, "+a+".0,\n "+a+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "}(t.shape,e,n,r):new function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "}(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeBilinearBackprop=function(t,e,n){var r=new function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],o=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?i-1:i,n&&u>1?o-1:o],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=c[0]/l[0],d=c[1]/l[1],h=1/f,p=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(p)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}(t,e,n);return this.compileAndRun(r,[t])},t.prototype.resizeNearestNeighbor=function(t,e,n,r){var i=new function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],c=[r&&e>1?e-1:e,r&&n>1?n-1:n],l=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+l+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],o=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&s>1?i-1:i,n&&u>1?o-1:o],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=c[0]/l[0],d=c[1]/l[1],h=1/f,p=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(p)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+c[0]+") *\n (float(dyR) / float("+l[0]+"));\n\n float sourceFracCol =\n float("+c[1]+") *\n (float(dyC) / float("+l[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}(t,e,n);return this.compileAndRun(r,[t])},t.prototype.multinomial=function(t,e,n,r){var i=e?t:qr(t),o=i.shape[0],a=i.shape[1],s=new xo(o,a,n),u=this.makeOutputArray(s.outputShape,"int32"),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],u,c)},t.prototype.oneHot=function(t,e,n,r){var i=new function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "}(t.size,e,n,r);return this.compileAndRun(i,[t])},t.prototype.nonMaxSuppression=function(t,e,n,r,i){return Ye("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),pi(t.dataSync(),e.dataSync(),n,r,i)},t.prototype.cropAndResize=function(t,e,n,r,i,o){var a=new function(t,e,n,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=t[0],a=t[1],s=t[2],u=t[3],c=e[0],l=n[0],f=n[1];this.outputShape=[c,l,f,u];var d="bilinear"===r?1:0,h=[a-1+".0",s-1+".0"],p=h[0],m=h[1],g=l>1?[""+(a-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],v=g[0],b=g[1],y=g[2],w=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],k=w[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+x+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+o+") {\n return;\n }\n\n float height_scale = "+b+";\n float width_scale = "+_+";\n\n float in_y = "+y+";\n if( in_y < 0.0 || in_y > "+p+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+k+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+d+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "}(t.shape,e.shape,r,i,o);return this.compileAndRun(a,[t,e,n])},t.prototype.depthToSpace=function(t,e,n){w(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],o="NHWC"===n?t.shape[2]:t.shape[3],a="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=o*e,c=a/(e*e),l=new $i("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},t.prototype.split=function(t,e,n){return gi(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=Nr(0,t,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/a,a],l=t.reshape([o,i]),f=e.reshape([o,a]);if(0===u)return si(gn([]),n);var d=bn(0),h=new ko(o,i,l.rank,f.rank,s,c);return this.compileAndRun(h,[f,l,d]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var i=Nr(0,t,n),o=i.sliceRank,a=i.numUpdates,s=i.strides,u=i.outputSize,c=new ko(a,o,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new Gi("return real * expR - imag * expI;",t.shape,e),i=new Gi("return real * expI + imag * expR;",t.shape,e),o=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],a=this.compileAndRun(r,o),s=this.compileAndRun(i,o),u=this.complex(a,s).as2D(t.shape[0],t.shape[1]);return a.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=Ar(t,e),o=i[0],a=i[1],s=i[2],u=i[3],c=e.reshape([a,r]),l=t.reshape([t.size/s,s]),f=new function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Ii(e.length),i=Ii(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "}(r,u,[a,s]);return this.compileAndRun(f,[l,c]).reshape(o)},t.prototype.fill=function(t,e,n){if("string"===(n=n||$(e))){var r=R(n,S(t));return r.fill(e),pt.make(t,{values:r},n)}var i=new Ki(t,e),o=i.getCustomSetupFunc(e),a=this.makeOutputArray(t,n);return this.compileAndRun(i,[],a,o)},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},t.prototype.linspace=function(t,e,n){return ui(t,e,n)},t.prototype.makeOutputArray=function(t,e){return pt.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=pt.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=xi("rc",e),r=Ii(e),i=function(t,e){if(1===t)return"rc";for(var n="",r=0;r "+e[0];for(var r="",i=t-2;i= "+e[i],i= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),a=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var o=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),a=2;a= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+i+") {\n setOutput(vec4(0));\n } else {\n "+o+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}}(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},t.prototype.packedReshape=function(t,e){var n=t.reshape([pe(t.shape)].concat(me(t.shape))),r=new function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+ki(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Si(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "}([pe(e)].concat(me(e)),n.shape);return this.compileAndRun(r,[n]).reshape(e)},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,i=n.shape,o=n.dtype,a=ge(i),s=Yi(i),u=this.makeTensorHandle(i,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=o,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=_i();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ki(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "}(a,s):new function(t,e){this.variableNames=["A"];var n=_i();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ki(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "}(a,s),this.compileAndRun(e,[{shape:a,dtype:o,dataId:t}],u,null,!0),u},t.prototype.compileAndRun=function(t,e,n,r,i){var o=this;if(void 0===i&&(i=!1),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=j(n.dtype,0),n;var a=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&S(e.shape)<=h.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?o.unpackTensor(e):o.packTensor(e),n=o.texData.get(e.dataId);else if(n.isPacked&&!ye(n.shape,e.shape)){var r=e,i=e.shape;e.shape=n.shape,e=o.packedReshape(e,i),n=o.texData.get(e.dataId),r.shape=i}return o.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},c=function(t,e,n){var r="";a.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(t,0,u),l=this.getAndSaveBinary(c,function(){return function(t,e,n,r){var i=e.userCode,o=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),a=o.map(function(t){return t.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=function(t,e,n,r){var i=[];t.forEach(function(t){var e=S(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?i.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var o,a,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n;switch(e.shapeInfo.logicalShape.length){case 0:return"\n vec4 get"+(n=e.name).charAt(0).toUpperCase()+n.slice(1)+"() {\n return "+_i().texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=_i();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+i[0]+", "+i[1]+", index);\n return "+o.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,o=i[0],a=i[1],s=_i();if(null!=i&&E(e,i))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+o+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===n[0]){var s=Di(e,n.slice(1));return"\n "+t(s)+"\n vec4 "+i+"(int b, int row, int col) {\n return "+i+"("+ji(["b","row","col"],[1,2])+");\n }\n "}var u=a[0],c=a[1],l=Math.ceil(n[2]/2);return"\n vec4 "+i+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+u+", "+c+", "+l*Math.ceil(n[1]/2)+", "+l+", b, row, col);\n return "+_i().texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=a[0],u=a[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),f="int b, int row, int col",d="b * "+l+" + (row / 2) * "+c+" + (col / 2)",h=2;h=1?"coords = 0;":c.map(function(t){return"coords."+d[t+f]+" = 0;"}).join("\n"),r=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+d[e+f]}).join(", ");var h="return outputValue;",p=1===S(t.shapeInfo.logicalShape),m=1===S(e.logicalShape);if(1!==s||p||m){if(p&&!m)h=1===u?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(c.length){var g=s-2,v=s-1;c.indexOf(g)>-1&&c.indexOf(v)>-1?h="return vec4(outputValue.x);":c.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}}else h="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+l+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+r+");\n "+h+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",o=e.texShape,a=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&E(a,o))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c=Ii(u),l=Gr(t.shapeInfo.logicalShape,e.logicalShape),f=u-s,d=["x","y","z","w","u","v"];return"\n float "+i+"() {\n "+c+" coords = getOutputCoords();\n "+(0===s?"":u<2&&l.length>=1?"coords = 0;":l.map(function(t){return"coords."+d[t+f]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+d[e+f]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),c=e.texShape,l=_i(),f="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+l.texture2D+"(textureSampler, uv).r;\n }\n ",d=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n #define isnan(value) isnan_custom(value)\n "+t.defineSpecialNaN+"\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+Oi+"\n "+Ai+"\n "+Ci+"\n "}(l);return e.isPacked?(o=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(E(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=(o=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+i[0]+", "+i[1]+"));\n int index = resTexRC.x * "+i[1]+" + resTexRC.y;\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+o+");\n int c = imod(index, "+o+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),i=r*Math.ceil(t[t.length-2]/2),o=i,a="",s="b, r, c",u=2;u0?32:16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,i=n.dtype,o=n.values,a=n.texture,s=n.usage,u=n.isPacked;if(null==a){var c,l=null!=this.activeTimers;l&&(c=performance.now());var f=n.texShape;if(null==f&&(f=ve(r,u),n.texShape=f),null!=o){var d=ge(r),h=void 0,p=f[1],m=f[0],g=o instanceof Uint8Array;u?(p=(e=Ji(f[0],f[1]))[0],h=new function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=_i(),i=e[0],o=e[1];this.outputShape=t;var a="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;a+="\n localCoords = coords;\n if(localCoords[2] + "+c+" < "+t[2]+") {\n localCoords[2] += "+c+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex /= 4;\n r = flatIndex / "+o+";\n c = imod(flatIndex, "+o+");\n uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+i+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+l+"] = values[0];\n } else if(offset == 1) {\n result["+l+"] = values[1];\n } else if(offset == 2) {\n result["+l+"] = values[2];\n } else {\n result["+l+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Si(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n \n "+a+"\n\n "+r.output+" = "+s+";\n }\n "}(d,[m=e[1],p],g)):h=new function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=_i(),i=e[0],o=e[1];this.outputShape=t;var a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode="\n "+Si(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex /= 4;\n int r = flatIndex / "+o+";\n int c = imod(flatIndex, "+o+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+i+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+a+", 0., 0., 0.);\n }\n "}(d,[m,p],g);var v=this.makeTensorHandle([m,p],i);this.texData.get(v.dataId).usage=g?Vi.PIXELS:Vi.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),p,m,o);var b=this.makeTensorHandle(h.outputShape,v.dtype);b.size=S(h.outputShape),this.texData.get(b.dataId).isPacked=u,this.compileAndRun(h,[v],b);var y=this.texData.get(b.dataId);n.texture=y.texture,n.texShape=y.texShape,n.isPacked=y.isPacked,n.usage=y.usage,this.disposeData(v.dataId),this.texData.delete(b.dataId),n.values=null,l&&(this.uploadWaitMs+=performance.now()-c)}else{var w=this.acquireTexture(f,s,i,u);n.texture=w}}},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},t.prototype.computeBytes=function(t,e){return t[0]*t[1]*U(e)},t}();Dt()&&It.registerBackend("webgl",function(){return new zo},2);var Lo=dn({abs_:function(t){var e=Qe(t,"x","abs");return"complex64"===e.dtype?It.runKernel(function(t){return t.complexAbs(e)},{$x:e}):It.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),Bo=dn({acos_:function(t){var e=Qe(t,"x","acos");return It.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(bn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),Uo=dn({acosh_:function(t){var e=Qe(t,"x","acosh");return It.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),Wo=dn({asin_:function(t){var e=Qe(t,"x","asin");return It.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(bn(1).sub(n.toFloat().square()).sqrt())}}})}}),qo=dn({asinh_:function(t){var e=Qe(t,"x","asinh");return It.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(bn(1).add(n.toFloat().square()).sqrt())}}})}}),Vo=dn({atan_:function(t){var e=Qe(t,"x","atan");return It.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),Ho=dn({atanh_:function(t){var e=Qe(t,"x","atanh");return It.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(bn(1).sub(n.toFloat().square()))}}})}}),$o=dn({ceil_:function(t){var e=Qe(t,"x","ceil");return It.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),Go=dn({clipByValue_:function(t,e,n){var r=Qe(t,"x","clipByValue");return w(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),It.runKernel(function(t,i){var o=t.clip(r,e,n);return i([r]),o},{$x:r},function(t,r){var i=r[0];return{$x:function(){return t.where(i.greaterEqual(e).logicalAnd(i.lessEqual(n)),Tn(t))}}})}}),Ko=dn({cos_:function(t){var e=Qe(t,"x","cos");return It.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),Xo=dn({cosh_:function(t){var e=Qe(t,"x","cosh");return It.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),Yo=dn({erf_:function(t){var e=Qe(t,"x","erf");return w("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),It.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),Jo=dn({exp_:function(t){var e=Qe(t,"x","exp");return It.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),Zo=dn({expm1_:function(t){var e=Qe(t,"x","expm1");return It.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),Qo=dn({floor_:function(t){var e=Qe(t,"x","floor");return It.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),ta=dn({log_:function(t){var e=Qe(t,"x","log");return It.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),ea=dn({log1p_:function(t){var e=Qe(t,"x","log1p");return It.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),na=dn({logSigmoid_:function(t){var e=Qe(t,"x","logSigmoid");return It.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),ra=dn({neg_:function(t){var e=Qe(t,"x","neg");return It.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),ia=dn({reciprocal_:function(t){var e=Qe(t,"x","reciprocal");return It.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),oa=dn({round_:function(t){var e=Qe(t,"x","round");return It.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),aa=dn({rsqrt_:function(t){var e=Qe(t,"x","rsqrt");return It.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),sa=dn({sigmoid_:function(t){var e=Qe(t,"x","sigmoid");return It.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(bn(1).sub(n)))}}})}}),ua=dn({sign_:function(t){var e=Qe(t,"x","sign");return It.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),ca=dn({isNaN_:function(t){var e=Qe(t,"x","isNaN");return It.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),la=dn({isInf_:function(t){var e=Qe(t,"x","isInf");return It.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),fa=dn({isFinite_:function(t){var e=Qe(t,"x","isFinite");return It.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return Tn(t)}}})}}),da=dn({sin_:function(t){var e=Qe(t,"x","sin");return It.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),ha=dn({sinh_:function(t){var e=Qe(t,"x","sinh");return It.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),pa=dn({softplus_:function(t){var e=Qe(t,"x","softplus");return It.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),ma=dn({sqrt_:function(t){var e=Qe(t,"x","sqrt");return It.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),ga=dn({square_:function(t){var e=Qe(t,"x","square");return It.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),va=dn({step_:function(t,e){void 0===e&&(e=0);var n=Qe(t,"x","step");return It.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return Tn(t)}}})}}),ba=dn({tan_:function(t){var e=Qe(t,"x","tan");return It.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),ya=dn({tanh_:function(t){var e=Qe(t,"x","tanh");return It.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return bn(1).sub(n.square()).mulStrict(t)}}})}});function wa(t,e,n,r,i,o){var a,s,u=Qe(t,"x","batchNorm"),c=Qe(e,"mean","batchNorm"),l=Qe(n,"variance","batchNorm");return null!=i&&(a=Qe(i,"scale","batchNorm")),null!=r&&(s=Qe(r,"offset","batchNorm")),w(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),w(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),w(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),null!=a&&w(2===a.rank||1===a.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."}),null!=s&&w(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),ka(u,c,l,s,a,o)}function xa(t,e,n,r,i,o){var a,s,u=Qe(t,"x","batchNorm"),c=Qe(e,"mean","batchNorm"),l=Qe(n,"variance","batchNorm");return null!=i&&(a=Qe(i,"scale","batchNorm")),null!=r&&(s=Qe(r,"offset","batchNorm")),w(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),w(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),w(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),null!=a&&w(3===a.rank||1===a.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."}),null!=s&&w(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),ka(u,c,l,s,a,o)}function _a(t,e,n,r,i,o){var a,s,u=Qe(t,"x","batchNorm"),c=Qe(e,"mean","batchNorm"),l=Qe(n,"variance","batchNorm");return null!=i&&(a=Qe(i,"scale","batchNorm")),null!=r&&(s=Qe(r,"offset","batchNorm")),w(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),w(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),w(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),null!=a&&w(4===a.rank||1===a.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."}),null!=s&&w(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),ka(u,c,l,s,a,o)}function ka(t,e,n,r,i,o){null==o&&(o=.001);var a,s,u,c=Qe(t,"x","batchNorm"),l=Qe(e,"mean","batchNorm"),f=Qe(n,"variance","batchNorm");return null!=i&&(a=Qe(i,"scale","batchNorm")),null!=r&&(s=Qe(r,"offset","batchNorm")),w(l.rank===f.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),w(null==s||l.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),w(null==a||l.rank===a.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c,It.runKernel(function(t,e){var n=t.batchNormalization(u,Sa(l),Sa(f),o,Sa(a),Sa(s));return e([c,l,f,a]),n},{$x:c,$mean:l,$variance:f,$scale:a,$offset:s},function(t,e){var n=e,r=n[0],i=n[1],a=n[2],s=n[3],c=null==s?bn(1):s,l=Kr(i.shape,u.shape),f=[];if(1===i.rank){for(var d=0;d=2&&a.rank>=2&&o.rank===a.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+a.rank+"."}),w(E(f,d),function(){return"Error in matMul: outer dimensions ("+f+") and ("+d+") of Tensors with shapes "+o.shape+" and "+a.shape+" must match."}),w(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var m=o.shape.slice(0,-2).concat([c,l]),g=n?o.as3D(h,s,c):o.as3D(h,c,s),v=r?a.as3D(p,l,u):a.as3D(p,u,l);return It.runKernel(function(t,e){var i=t.batchMatMul(g,v,n,r);return e([g,v]),i},{$a:g,$b:v},function(t,e){var i=e,o=i[0],a=i[1];return n||r?!n&&r?{$a:function(){return t.matMul(a,!1,!1)},$b:function(){return t.matMul(o,!0,!1)}}:n&&!r?{$a:function(){return a.matMul(t,!1,!0)},$b:function(){return o.matMul(t,!1,!1)}}:{$a:function(){return a.matMul(t,!0,!0)},$b:function(){return t.matMul(o,!0,!0)}}:{$a:function(){return t.matMul(a,!1,!0)},$b:function(){return o.matMul(t,!0,!1)}}}).reshape(m)}}),Ha=dn({dot_:function(t,e){var n=Qe(t,"t1","dot"),r=Qe(e,"t2","dot");w(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var i=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];return w(i===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+o+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),$a=dn({outerProduct_:function(t,e){var n=Qe(t,"v1","outerProduct"),r=Qe(e,"v2","outerProduct");return w(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Ga=dn({reverse_:function(t,e){var n=Qe(t,"x","reverse");if(0===n.rank)return n.clone();var r=I(e,n.shape);return It.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),Ka=dn({reverse1d_:function(t){var e=Qe(t,"x","reverse");return w(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Ga(e,0)}}),Xa=dn({reverse2d_:function(t,e){var n=Qe(t,"x","reverse");return w(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Ga(n,e)}}),Ya=dn({reverse3d_:function(t,e){var n=Qe(t,"x","reverse");return w(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Ga(n,e)}}),Ja=dn({reverse4d_:function(t,e){var n=Qe(t,"x","reverse");return w(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Ga(n,e)}});function Za(t,e,n,r,i,o){var a=Qe(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),w(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),w(oi(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=o&&w(O(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var c=Yr(s.shape,e,n,r,i,o),l=It.runKernel(function(t,e){var n=t.maxPool(s,c);return e([s,n]),n},{x:s},function(t,o){var a=o[0],s=o[1];return{x:function(){return function(t,e,n,r,i,o,a,s){var u=Qe(t,"dy","maxPoolBackprop"),c=Qe(e,"input","maxPoolBackprop"),l=Qe(n,"output","maxPoolBackprop");w(c.rank===u.rank,function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"}),null==o&&(o=[1,1]),w(oi(i,o),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"}),w(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),w(4===c.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."});var f=Yr(c.shape,r,i,o,a,void 0);return It.runKernel(function(t){return t.maxPoolBackprop(u,c,l,f)},{$dy:u,$input:c})}(t,a,s,e,n,r,i)}}});return u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function Qa(t,e,n,r,i,o){var a=Qe(t,"x","avgPool","float32");null==r&&(r=[1,1]),w(oi(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),w(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=o&&w(O(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var c=Yr(s.shape,e,n,r,i,o),l=It.runKernel(function(t){return t.avgPool(s,c)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,o){var a=Qe(t,"dy","avgPoolBackprop"),s=Qe(e,"input","avgPoolBackprop");w(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"}),null==i&&(i=[1,1]),w(oi(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,c=a,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),w(4===c.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."}),w(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var f=Yr(u.shape,n,r,i,o),d=It.runKernel(function(t){return t.avgPoolBackprop(c,u,f)},{dy4D:c,input4D:u});return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}(t,s,e,n,r,i)}}});return l=l.cast(a.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var ts=dn({maxPool_:function(t,e,n,r,i){return Za(t,e,n,1,r,i)}}),es=dn({avgPool_:function(t,e,n,r,i){return Qa(t,e,n,1,r,i)}}),ns=dn({pool_:function(t,e,n,r,i,o){null==i&&(i=[1,1]),null==o&&(o=1),0===r&&(r="valid");var a=Qe(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),w(oi(o,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"});var c,l=Yr(s.shape,e,o,i,r),f=[l.dilationHeight,l.dilationWidth];c="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([l.filterHeight,l.filterWidth],f):[[0,0],[0,0]];var d=1===f[0]&&1===f[1],h=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),o=t.concat(r,i),a=e.map(function(t,e){return(t-o[e]%t)%t}),s=i.map(function(t,e){return t+a[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,a[e]]})]}([l.inHeight,l.inWidth],f,c),p=h[0],m=h[1],g=d?r:"valid",v=d?s:mr(s,f,p),b=("avg"===n?function(){return Qa(v,e,o,1,g)}:function(){return Za(v,e,o,1,g)})(),y=d?b:Jn(b,f,m);return u?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}}),rs=dn({slice_:function(t,e,n){var r,i,o=Qe(t,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(o.rank-1).fill(0)):e.length=0?t:(w(-1===t,function(){return"Bad value in size"}),o.shape[e]-r[e])}),function(t,e,n){w(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),w(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){w(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},i=0;i0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Kr(i.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),Ds=dn({addN_:function(t){w(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),w(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Qe(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!E(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return It.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),js=dn({addStrict_:function(t,e){var n=Qe(t,"a","addStrict"),r=Qe(e,"b","addStrict");return x(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Rs=dn({atan2_:function(t,e){var n,r=Qe(t,"a","atan2"),i=Qe(e,"b","atan2");n=Et(r,i),r=n[0],i=n[1];var o=Xr(r.shape,i.shape);return It.runKernel(function(t,e){var n=t.atan2(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Is(n.square(),r.square()),i=t.mul(r.div(e)),a=Kr(n.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(n.shape)},$b:function(){var e=Is(n.square(),r.square()),i=ra(t.mul(n.div(e))),a=Kr(r.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(r.shape)}}})}}),Fs=dn({div_:function(t,e){var n,r=Qe(t,"a","div"),i=Qe(e,"b","div");if(n=Et(r,i),r=n[0],i=n[1],"int32"===r.dtype&&"int32"===i.dtype)return zs(r,i);var o=Xr(r.shape,i.shape);return It.runKernel(function(t,e){var n=t.realDivide(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Kr(n.shape,o);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Kr(r.shape,o);i.length>0&&(e=e.sum(i).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}})}}),Ps=dn({divStrict_:function(t,e){var n=Qe(t,"a","div"),r=Qe(e,"b","div");return x(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),zs=dn({floorDiv_:function(t,e){var n,r=Qe(t,"a","floorDiv"),i=Qe(e,"b","floorDiv");n=Et(r,i),r=n[0],i=n[1];var o=Xr(r.shape,i.shape);return It.runKernel(function(t,e){var n=t.floorDiv(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Kr(n.shape,o);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Kr(r.shape,o);i.length>0&&(e=e.sum(i).reshape(r.shape));var a=r.square();return e.div(a.toFloat()).neg()}}})}}),Ls=dn({maximum_:function(t,e){var n,r=Qe(t,"a","maximum"),i=Qe(e,"b","maximum");return n=Et(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Xr(r.shape,i.shape),It.runKernel(function(t,e){var n=t.maximum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),Bs=dn({maximumStrict_:function(t,e){var n=Qe(t,"a","maximumStrict"),r=Qe(e,"b","maximumStrict");return x(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Us=dn({minimum_:function(t,e){var n,r=Qe(t,"a","minimum"),i=Qe(e,"b","minimum");return n=Et(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Xr(r.shape,i.shape),It.runKernel(function(t,e){var n=t.minimum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),Ws=dn({minimumStrict_:function(t,e){var n=Qe(t,"a","minimumStrict"),r=Qe(e,"b","minimumStrict");return x(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),qs=dn({mod_:function(t,e){var n,r=Qe(t,"a","mod"),i=Qe(e,"b","mod");n=Et(r,i),r=n[0],i=n[1];var o=Xr(r.shape,i.shape);return It.runKernel(function(t,e){var n=t.mod(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Kr(n.shape,o);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),i=Kr(r.shape,o);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),Vs=dn({modStrict_:function(t,e){var n=Qe(t,"a","modStrict"),r=Qe(e,"b","modStrict");return x(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Hs=dn({mul_:function(t,e){var n,r=Qe(t,"a","mul"),i=Qe(e,"b","mul");n=Et(r,i),r=n[0],i=n[1];var o=Xr(r.shape,i.shape);return It.runKernel(function(t,e){var n=t.multiply(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),i=Kr(n.shape,o);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Kr(r.shape,o);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),$s=dn({mulStrict_:function(t,e){var n=Qe(t,"a","mul"),r=Qe(e,"b","mul");return x(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Gs=dn({pow_:function(t,e){var n=Qe(t,"base","pow"),r=Qe(e,"exp","pow"),i=Xr(n.shape,r.shape);return t=n.cast(kt(n.dtype,r.dtype)),e=r.cast(kt(n.dtype,r.dtype)),It.runKernel(function(t,e){var i=t.pow(n,r);return e([n,r,i]),i},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],o=e[2];return{$base:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(bn(1))))),a=Kr(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},$exp:function(){var e=n.greater(0),a=n.log().where(e,Tn(n)),s=t.mul(o.mul(a)),u=Kr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),Ks=dn({powStrict_:function(t,e){return x(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Xs=dn({squaredDifference_:function(t,e){var n,r=Qe(t,"a","squaredDifference"),i=Qe(e,"b","squaredDifference");return n=Et(r,i),r=n[0],i=n[1],Xr(r.shape,i.shape),It.runKernel(function(t,e){var n=t.squaredDifference(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1],i=bn(2);return{$a:function(){return t.mul(n.sub(r).mul(i))},$b:function(){return t.mul(r.sub(n).mul(i))}}})}}),Ys=dn({squaredDifferenceStrict_:function(t,e){var n=Qe(t,"a","squaredDifferenceStrict"),r=Qe(e,"b","squaredDifferenceStrict");return x(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Js=dn({sub_:function(t,e){var n,r=Qe(t,"a","sub"),i=Qe(e,"b","sub");n=Et(r,i),r=n[0],i=n[1];var o=Xr(r.shape,i.shape);return It.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=Kr(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Kr(i.shape,o);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),Zs=dn({subStrict_:function(t,e){var n=Qe(t,"a","subStrict"),r=Qe(e,"b","subStrict");return x(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),Qs=dn({logicalAnd_:function(t,e){var n=Qe(t,"a","logicalAnd","bool"),r=Qe(e,"b","logicalAnd","bool");return Xr(n.shape,r.shape),It.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),tu=dn({logicalNot_:function(t){var e=Qe(t,"x","logicalNot","bool");return It.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),eu=dn({logicalOr_:function(t,e){var n=Qe(t,"a","logicalOr","bool"),r=Qe(e,"b","logicalOr","bool");return Xr(n.shape,r.shape),It.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),nu=dn({logicalXor_:function(t,e){var n=Qe(t,"a","logicalXor","bool"),r=Qe(e,"b","logicalXor","bool");return Xr(n.shape,r.shape),eu(t,e).logicalAnd(Qs(t,e).logicalNot())}}),ru=dn({where_:function(t,e,n){var r=Qe(e,"a","where"),i=Qe(n,"b","where"),o=Qe(t,"condition","where","bool");return x(r.shape,i.shape,"Error in where: "),1===o.rank?w(o.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):x(o.shape,i.shape,"Error in where: "),It.runKernel(function(t,e){var n=t.select(o,r,i);return e([o]),n},{$condition:o,$a:r,$b:i},function(t,e){var n=e[0];return{$condition:function(){return Tn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),iu=function(t){return c(this,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return[4,(e=Qe(t,"condition","whereAsync","bool")).data()];case 1:return n=i.sent(),r=yi(e.shape,n),t!==e&&e.dispose(),[2,r]}})})},ou=dn({elu_:function(t){var e=Qe(t,"x","elu");return It.runKernel(function(t,n){var r=t.elu(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return It.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),au=dn({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=Qe(t,"x","leakyRelu");return Ls(bn(e).mul(n),n)}}),su=dn({prelu_:function(t,e){var n=Qe(t,"x","prelu"),r=Qe(e,"alpha","prelu");return It.runKernel(function(t,e){var i=t.prelu(n,r);return e([n,r]),i},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],i=n.greater(0);return{$x:function(){return ru(i,t,t.mul(r))},$alpha:function(){var e=ru(i,Tn(t),t.mul(n)),o=Kr(r.shape,t.shape);return o.length>0&&(e=e.sum(o)),e.reshape(r.shape)}}})}}),uu=dn({relu_:function(t){var e=Qe(t,"x","relu");return"bool"===e.dtype?e.toInt():It.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),cu=dn({selu_:function(t){var e=Qe(t,"x","selu");return It.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(bn(0)),r=bn(1.7580993408473768),i=bn(1.0507009873554805),o=t.mul(i),a=t.mul(r).mul(n.toFloat().exp());return ru(e,o,a)}}})}}),lu=dn({transpose_:function(t,e){var n=Qe(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),w(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){w(t>=0&&ti)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var o=It.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:o[0],indices:o[1]}}}),_u=dn({scatterND_:function(t,e,n){var r=Qe(t,"indices","scatterND","int32"),i=Qe(e,"updates","scatterND");return function(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,i=e.rank>1?e.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rankr){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(On(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=hn(n,u).as2D(i,r),l=ku(c),f=Math.floor(r/2)+1,d=pn(l),h=mn(l),p=d.split([f,r-f],d.shape.length-1),m=h.split([f,r-f],h.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=f,hn(p[0],m[0]).reshape(g)}}),Ou=dn({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=Su(r);return pn(i)}var o=[n,2*(e-1)],a=pn(t).as2D(n,e),s=mn(t).as2D(n,e),u=a.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(bn(-1)),l=a.concat(u,1),f=s.concat(c,1);return r=hn(l,f).as2D(o[0],o[1]),i=Su(r),pn(i)}}),Au=Object.freeze({fft:ku,ifft:Su,rfft:Eu,irfft:Ou}),Cu=dn({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=Qe(t,"sparseIndices","sparseToDense","int32"),o=Qe(e,"sparseValues","sparseToDense"),a=Qe(r,"defaultValue","sparseToDense",o.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var i=t.rank>0?t.shape[0]:1,o=t.rank>1?t.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var a=e.size;if(0!==e.rank&&(1!==e.rank||a!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,o,n,a),It.runKernel(function(t){return t.sparseToDense(i,o,n,a)},{$sparseIndices:i,$sparseValues:o,$defaultValue:a})}}),Mu=dn({gatherND_:function(t,e){var n=Qe(e,"indices","gatherND","int32"),r=Qe(t,"x","gatherND");return It.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}}),Nu=dn({dropout_:function(t,e,n,r){if(null!=n&&!E(t.shape,n))throw new Error("Non-default noise shape is not implemented yet: "+JSON.stringify(n));var i=hr(t.shape,0,1,"float32",r).greater(e);return i=i.div(Js(1,e)),t.mul(i)}});function Tu(t,e,n){for(var r=1-t%2,i=new Float32Array(t),o=0;o1?s.div(bn(a)):s}if(n===Iu.SUM_BY_NONZERO_WEIGHTS){if(null==i)return o.sum().div(bn(r.size));var u=i.mul(En(r.shape)).notEqual(bn(0)).sum().toFloat();return o.sum().div(u)}throw Error("Unknown reduction: "+n)}}),Lu=dn({cosineDistance_:function(t,e,n,r,i){void 0===i&&(i=Iu.SUM_BY_NONZERO_WEIGHTS);var o=Qe(t,"labels","cosineDistance"),a=Qe(e,"predictions","cosineDistance"),s=null;null!=r&&(s=Qe(r,"weights","cosineDistance")),x(o.shape,a.shape,"Error in cosineDistance: ");var u=bn(1).sub(o.mul(a).sum(n,!0));return zu(u,s,i)}}),Bu=dn({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Iu.SUM_BY_NONZERO_WEIGHTS);var i=Qe(t,"labels","hingeLoss"),o=Qe(e,"predictions","hingeLoss"),a=null;null!=n&&(a=Qe(n,"weights","hingeLoss")),x(i.shape,o.shape,"Error in hingeLoss: ");var s=bn(1);i=bn(2).mul(i).sub(s);var u=s.sub(i.mul(o)).relu();return zu(u,a,r)}}),Uu=dn({huberLoss_:function(t,e,n,r,i){void 0===r&&(r=1),void 0===i&&(i=Iu.SUM_BY_NONZERO_WEIGHTS);var o=Qe(t,"labels","huberLoss"),a=Qe(e,"predictions","huberLoss"),s=null;null!=n&&(s=Qe(n,"weights","huberLoss")),x(o.shape,a.shape,"Error in huberLoss: ");var u=bn(r),c=a.sub(o).abs(),l=Us(c,u),f=c.sub(l),d=bn(.5).mul(l.square()).add(u.mul(f));return zu(d,s,i)}}),Wu=dn({logLoss_:function(t,e,n,r,i){void 0===r&&(r=1e-7),void 0===i&&(i=Iu.SUM_BY_NONZERO_WEIGHTS);var o=Qe(t,"labels","logLoss"),a=Qe(e,"predictions","logLoss"),s=null;null!=n&&(s=Qe(n,"weights","logLoss")),x(o.shape,a.shape,"Error in logLoss: ");var u=bn(1),c=bn(r),l=o.mul(a.add(c).log()).neg().sub(u.sub(o).mul(u.sub(a).add(c).log()));return zu(l,s,i)}}),qu=dn({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Iu.SUM_BY_NONZERO_WEIGHTS);var i=Qe(t,"labels","meanSquaredError"),o=Qe(e,"predictions","meanSquaredError"),a=null;null!=n&&(a=Qe(n,"weights","meanSquaredError")),x(i.shape,o.shape,"Error in meanSquaredError: ");var s=i.squaredDifference(o);return zu(s,a,r)}}),Vu=dn({sigmoidCrossEntropy_:function(t,e,n,r,i){void 0===r&&(r=0),void 0===i&&(i=Iu.SUM_BY_NONZERO_WEIGHTS);var o=Qe(t,"multiClassLabels","sigmoidCrossEntropy"),a=Qe(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Qe(n,"weights","sigmoidCrossEntropy")),x(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=bn(r),c=bn(1),l=bn(.5);o=o.mul(c.sub(u)).add(l.mul(u))}var f=function(t,e){var n=Qe(t,"labels","sigmoidCrossEntropyWithLogits"),r=Qe(e,"logits","sigmoidCrossEntropyWithLogits");x(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),o=r.mul(n),a=r.abs().neg().exp().log1p();return i.sub(o).add(a)}(o,a);return zu(f,s,i)}}),Hu=dn({softmaxCrossEntropy_:function(t,e,n,r,i){void 0===r&&(r=0),void 0===i&&(i=Iu.SUM_BY_NONZERO_WEIGHTS);var o=Qe(t,"onehotLabels","softmaxCrossEntropy"),a=Qe(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Qe(n,"weights","softmaxCrossEntropy")),x(o.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){var u=bn(r),c=bn(1),l=bn(o.shape[1]);o=o.mul(c.sub(u)).add(u.div(l))}var f=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Ur(function(t,e,r){var i=e.logSumExp([n],!0),o=e.toFloat().sub(i);return r([t,o]),{value:o.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],i=e[1],o=on(t.shape,[n]);return[t.reshape(o).mul(r.toFloat().sub(i.exp())),t.reshape(o).mul(i.exp().sub(r.toFloat()))]}}})(t,e)}(o,a);return zu(f,s,i)}}),$u=Object.freeze({get Reduction(){return Iu},absoluteDifference:Pu,computeWeightedLoss:zu,cosineDistance:Lu,hingeLoss:Bu,huberLoss:Uu,logLoss:Wu,meanSquaredError:qu,sigmoidCrossEntropy:Vu,softmaxCrossEntropy:Hu});function Gu(t,e){return void 0===e&&(e=!1),It.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],i=rr(n),o=t.clone(),a=wn([[1]],[1,1]),s=a.clone(),u=n>=r?r:n,c=function(t){var e,u=o,c=s,l=i;e=It.tidy(function(){var e=o.slice([t,t],[n-t,1]),u=e.norm(),c=o.slice([t,t],[1,1]),l=c.sign().neg(),f=c.sub(l.mul(u)),d=e.div(f);s=1===d.shape[0]?a.clone():a.concat(d.slice([1,0],[d.shape[0]-1,d.shape[1]]),0);var h=l.matMul(f).div(u).neg(),p=o.slice([t,0],[n-t,r]),m=h.mul(s);o=0===t?p.sub(m.matMul(s.transpose().matMul(p))):o.slice([0,0],[t,r]).concat(p.sub(m.matMul(s.transpose().matMul(p))),0);var g=i.slice([0,t],[n,i.shape[1]-t]);return i=0===t?g.sub(g.matMul(s).matMul(m.transpose())):i.slice([0,0],[n,t]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,o,i]}),s=e[0],o=e[1],i=e[2],ze([u,c,l])},l=0;lr&&(i=i.slice([0,0],[n,r]),o=o.slice([0,0],[r,r])),[i,o]})}var Ku=dn({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,w(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){w(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return Gu(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return wr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=Gu(t,e),o=n[0],a=n[1];r.push(o),i.push(a)}),[vr(r,0).reshape(t.shape),vr(i,0).reshape(t.shape)]}}),Yu=Object.freeze({gramSchmidt:Ku,qr:Xu});function Ju(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var o=t.shape[0];return n=Math.min(n,o),w(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),w(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),w(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),w(1===e.rank,function(){return"scores must be a 1D tensor"}),w(e.shape[0]===o,function(){return"scores has incompatible shape with boxes. Expected "+o+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var Zu=dn({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Qe(t,"images","resizeBilinear");w(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),w(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=It.runKernel(function(t,e){return e([i]),t.resizeBilinear(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return It.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Qu=dn({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Qe(t,"images","resizeNearestNeighbor");w(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),w(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),w("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=It.runKernel(function(t,e){return e([i]),t.resizeNearestNeighbor(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return It.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),tc=dn({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var o=Qe(t,"boxes","nonMaxSuppression"),a=Qe(e,"scores","nonMaxSuppression"),s=Ju(o,a,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,It.runKernel(function(t){return t.nonMaxSuppression(o,a,n,r,i)},{$boxes:o})}}),ec=dn({cropAndResize_:function(t,e,n,r,i,o){var a=Qe(t,"image","cropAndResize","float32"),s=Qe(e,"boxes","cropAndResize","float32"),u=Qe(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;var c=s.shape[0];return w(4===a.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."}),w(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),w(1===u.rank&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),w(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),w(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),w("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),It.runKernel(function(t,e){return t.cropAndResize(a,s,u,r,i,o)},{$image:a,$boxes:s})}}),nc=Object.freeze({resizeBilinear:Zu,resizeNearestNeighbor:Qu,nonMaxSuppression:tc,nonMaxSuppressionAsync:function(t,e,n,r,i){return void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),c(this,void 0,void 0,function(){var o,a,s,u,c,f;return l(this,function(l){switch(l.label){case 0:return o=Qe(t,"boxes","nonMaxSuppressionAsync"),a=Qe(e,"scores","nonMaxSuppressionAsync"),s=Ju(o,a,n,r,i),n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,[4,o.data()];case 1:return u=l.sent(),[4,a.data()];case 2:return c=l.sent(),f=pi(u,c,n,r,i),o!==t&&o.dispose(),a!==e&&a.dispose(),[2,f]}})})},cropAndResize:ec}),rc=dn({matMul_:function(t,e,n,r,i,o){var a;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o="linear");var s=Qe(t,"a","fused matMul"),u=Qe(e,"b","fused matMul");a=Et(s,u),s=a[0],u=a[1];var c=n?s.shape[s.rank-2]:s.shape[s.rank-1],l=r?u.shape[u.rank-1]:u.shape[u.rank-2],f=n?s.shape[s.rank-1]:s.shape[s.rank-2],d=r?u.shape[u.rank-2]:u.shape[u.rank-1],h=s.shape.slice(0,-2),p=u.shape.slice(0,-2),m=S(h),g=S(p);w(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+"."}),w(E(h,p),function(){return"Error in fused matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match."}),w(c===l,function(){return"Error in fused matMul: inner shapes ("+c+") and ("+l+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var v,b=s.shape.slice(0,-2).concat([f,d]),y=n?s.as3D(m,c,f):s.as3D(m,f,c),x=r?u.as3D(g,d,l):u.as3D(g,l,d);null!=i&&Xr(b,(v=Et(v=Qe(i,"bias","fused matMul"),s)[0]).shape);var _={$a:y,$b:x};return null!=i&&(_.$bias=v),It.runKernel(function(t,e){var i=t.fusedBatchMatMul(y,x,n,r,v,o);return e([y,x,i]),i},_,function(t,e){var a,s=e[0],u=e[1],c=e[2];if(null==o||"linear"===o)a=t;else{if("relu"!==o)throw new Error("Gradient for activation "+o+" has not been implemented yet.");a=t.mul(c.step())}var l={};return null!=i&&(l={$bias:function(){var t=a,e=Kr(v.shape,a.shape);return e.length>0&&(t=t.sum(e)),t.reshape(v.shape)}}),n||r?!n&&r?Object.assign({$a:function(){return a.matMul(u,!1,!1)},$b:function(){return a.matMul(s,!0,!1)}},l):n&&!r?Object.assign({$a:function(){return u.matMul(a,!1,!0)},$b:function(){return s.matMul(a,!1,!1)}},l):Object.assign({$a:function(){return u.matMul(a,!0,!0)},$b:function(){return a.matMul(s,!0,!0)}},l):Object.assign({$a:function(){return a.matMul(u,!1,!0)},$b:function(){return s.matMul(a,!0,!1)}},l)}).reshape(b)}}),ic=Object.freeze({matMul:rc}),oc=Object.freeze({image:nc,linalg:Yu,losses:$u,spectral:Au,fused:ic,signal:Fu,op:dn,batchNormalization2d:Oa,batchNormalization3d:Aa,batchNormalization4d:Ca,batchNormalization:Ma,batchNorm:Na,batchNorm2d:Ta,batchNorm3d:Ia,batchNorm4d:Da,complex:hn,real:pn,imag:mn,concat:In,concat1d:Dn,concat2d:jn,concat3d:Rn,concat4d:Fn,split:Pn,conv1d:Pa,conv2d:za,conv3d:La,conv2dDerFilter:Ba,depthwiseConv2d:Ua,separableConv2d:Wa,conv2dTranspose:qa,matMul:Va,dot:Ha,outerProduct:$a,reverse:Ga,reverse1d:Ka,reverse2d:Xa,reverse3d:Ya,reverse4d:Ja,maxPool:ts,avgPool:es,pool:ns,slice:rs,slice1d:is,slice2d:os,slice3d:as,slice4d:ss,abs:Lo,acos:Bo,acosh:Uo,asin:Wo,asinh:qo,atan:Vo,atanh:Ho,ceil:$o,clipByValue:Go,cos:Ko,cosh:Xo,erf:Yo,exp:Jo,expm1:Zo,floor:Qo,log:ta,log1p:ea,logSigmoid:na,neg:ra,reciprocal:ia,round:oa,rsqrt:aa,sigmoid:sa,sign:ua,isNaN:ca,isInf:la,isFinite:fa,sin:da,sinh:ha,softplus:pa,sqrt:ma,square:ga,step:va,tan:ba,tanh:ya,all:cs,any:ls,argMax:fs,argMin:ds,logSumExp:hs,max:ps,mean:ms,min:gs,moments:vs,sum:bs,prod:ys,equal:ws,equalStrict:xs,greater:_s,greaterEqual:ks,greaterEqualStrict:Ss,greaterStrict:Es,less:Os,lessEqual:As,lessEqualStrict:Cs,lessStrict:Ms,notEqual:Ns,notEqualStrict:Ts,add:Is,addN:Ds,addStrict:js,atan2:Rs,div:Fs,divStrict:Ps,floorDiv:zs,maximum:Ls,maximumStrict:Bs,minimum:Us,minimumStrict:Ws,mod:qs,modStrict:Vs,mul:Hs,mulStrict:$s,pow:Gs,powStrict:Ks,squaredDifference:Xs,squaredDifferenceStrict:Ys,sub:Js,subStrict:Zs,elu:ou,leakyRelu:au,prelu:su,relu:uu,selu:cu,logicalAnd:Qs,logicalNot:tu,logicalOr:eu,logicalXor:nu,where:ru,whereAsync:iu,buffer:Xn,print:Yn,batchToSpaceND:Jn,cast:Zn,clone:Qn,cumsum:tr,depthToSpace:er,expandDims:nr,eye:rr,multinomial:ir,oneHot:or,pad:ar,pad1d:sr,pad2d:ur,pad3d:cr,pad4d:lr,rand:fr,randomNormal:dr,randomUniform:hr,reshape:pr,spaceToBatchND:mr,squeeze:gr,stack:vr,tile:br,truncatedNormal:yr,unstack:wr,setdiff1dAsync:xr,fill:An,linspace:Cn,ones:En,range:Mn,scalar:bn,tensor:gn,tensor1d:yn,tensor2d:wn,tensor3d:xn,tensor4d:_n,tensor5d:kn,tensor6d:Sn,zeros:On,onesLike:Nn,zerosLike:Tn,transpose:lu,softmax:qr,logSoftmax:Vr,localResponseNormalization:fu,norm:du,gather:mu,unsortedSegmentSum:gu,basicLSTMCell:vu,multiRNNCell:bu,movingAverage:yu,stridedSlice:wu,topk:xu,scatterND:_u,fft:ku,ifft:Su,rfft:Eu,irfft:Ou,sparseToDense:Cu,gatherND:Mu,dropout:Nu,hannWindow:Du,hammingWindow:ju,frame:Ru}),ac=function(){function t(){if(this.blockSize=48,this.firstUse=!0,h.get("IS_BROWSER")){var t=function(){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}();this.fromPixels2DContext=t.getContext("2d")}this.data=new Hr(this,It)}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,h.get("IS_NODE")&&Ye("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n})},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r;if(h.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(t instanceof ImageData||t.data instanceof Uint8Array)n=t.data;else{if(!(t instanceof HTMLImageElement||t instanceof HTMLVideoElement))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data}if(4===e)r=new Int32Array(n);else{var i=t.width*t.height;r=new Int32Array(i*e);for(var o=0;od&&(d=m,h=p)}u[l]=h}return a},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var i=kt(t.dtype,"int32"),o=On(t.shape,i),a=this.readSync(o.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],c=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},l=0;le?1:0})},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],l=0;l=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),an("max",e,t.rank);for(var n=rn(t.shape,e),r=n[0],i=n[1],o=On(r,t.dtype),a=S(i),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;cf&&(f=h)}s[c]=f}return o},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),an("all",e,t.rank);for(var n=rn(t.shape,e),r=n[0],i=n[1],o=On(r,t.dtype),a=S(i),s=this.readSync(o.dataId),u=this.readSync(t.dataId),c=0;c0?n[r]=1:n[r]=0;return pt.make(t.shape,{values:n})},t.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return pt.make(t.shape,{values:n})},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?i:Math.exp(i)-1}return pt.make(t.shape,{values:e})},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=this.readSync(t.dataId),o=0;o=1?i[o]:i[o]*(a+1)}return pt.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r=0?1.0507009873554805*i:1.7580993408473768*(Math.exp(i)-1)}return pt.make(t.shape,{values:e})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=this.readSync(t.dataId),o=0;on?n:a-e,s=r[i]0?1:e}return pt.make(t.shape,{values:n})},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=Xn(n.outShape,t.dtype),l=this.readSync(t.dataId),f=this.readSync(e.dataId),d=c.values,h=0;h=n.inHeight))for(var x=y*e.strides[0],_=p+w*t.strides[1],k=0;k=n.inWidth))for(var C=x+O*e.strides[1],M=_+A*n.inChannels,N=C,T=0;T=n.inDepth))for(var S=_*e.strides[0],E=v+k*t.strides[1],O=0;O=n.inHeight))for(var T=S+M*e.strides[1],I=E+N*t.strides[2],D=0;D=n.inWidth))for(var z=T+F*e.strides[2],L=I+P*n.inChannels,B=z,U=0;U=n.inHeight))for(var _=w*e.strides[0],k=m+x*t.strides[1],S=0;S=n.inWidth))for(var M=_+A*e.strides[1],N=k+C*n.inChannels,T=E,I=M,D=0;DT?T=P:"avg"===n&&(I+=P,D++)}if(isNaN(T))break}p[O+A*v+x]="avg"===n?I/D:T}return h.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=Xn(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,f=this.bufferSync(t),d=0;d_&&(_=C,k=E*u+A)}n.set(k,d,p,b,h)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),o=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,f=l-1-r.padInfo.left,d=c-1-r.padInfo.top,h=Xn(e.shape,"float32"),p=this.bufferSync(i),m=this.bufferSync(t),g=0;g=r.outHeight||Math.floor(S)!==S))for(var E=0;E=r.outWidth||Math.floor(O)!==O)){var A=c*l-1-p.get(g,S,O,v)===k*l+E?1:0;0!==A&&(_+=m.get(g,S,O,v)*A)}}}h.set(_,g,b,y,v)}return h.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,f=l-1-n.padInfo.left,d=c-1-n.padInfo.top,h=Xn(e.shape,"float32"),p=1/(o*a),m=this.bufferSync(t),g=0;g=n.outHeight||Math.floor(S)!==S))for(var E=0;E=n.outWidth||Math.floor(O)!==O||(_+=m.get(g,S,O,v))}}h.set(_*p,g,b,y,v)}return h.toTensor()},t.prototype.cast=function(t,e){return ai(t,e,this)},t.prototype.reshape=function(t,e){return si(t,e)},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var i=t.shape,o=i[0],a=i[1],s=i[2],u=i[3],c=this.readSync(t.dataId),l=new Float32Array(S([o,e,n,u])),f=[r&&e>1?a-1:a,r&&n>1?s-1:s],d=[r&&e>1?e-1:e,r&&n>1?n-1:n],h=0,p=f[0]/d[0],m=f[1]/d[1],g=0;g1?o-1:o,n&&l>1?a-1:a],h=[n&&c>1?c-1:c,n&&l>1?l-1:l],p=d[0]/h[0],m=d[1]/h[1],g=this.readSync(t.dataId),v=0,b=0;b1?a-1:a,r&&n>1?s-1:s],d=[r&&e>1?e-1:e,r&&n>1?n-1:n],h=f[0]/d[0],p=f[1]/d[1],m=0,g=0;g1?o-1:o,n&&l>1?a-1:a],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],m=h[0]/p[0],g=h[1]/p[1],v=1/m,b=1/g,y=2*Math.ceil(v)+2,w=2*Math.ceil(b)+2,x=0;x=c)){var R=_+j*t.strides[1],F=j*m;if(k===Math.min(o-1,n?Math.round(F):Math.floor(F)))for(var P=0;P=l)){var L=R+z*t.strides[2],B=z*g;A===Math.min(a-1,n?Math.round(B):Math.floor(B))&&(I+=d[L+T])}}}}f[C+T]=I}return _n(f,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,i,o){this.assertNotComplex([t,e,n,i,o],"batchNorm");for(var a=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=i?this.readSync(i.dataId):new Float32Array([1]),l=o?this.readSync(o.dataId):new Float32Array([0]),f=new Float32Array(a.length),d=l.length,h=c.length,p=u.length,m=s.length,g=0,v=0,b=0,y=0,w=0;w=d&&(g=0),v>=m&&(v=0),b>=h&&(b=0),y>=p&&(y=0);return _n(f,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var o=t.shape[3],a=o-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%o,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,a),u=0;r<=i;r++){var c=s[r];u+=c*c}return u}for(var f=0;f=0&&o[a]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],o=t.shape[2],a=t.shape[3],s=i*e,u=o*e,c=a/(e*e),l=this.readSync(t.dataId),f=new Float32Array(r*s*u*c),d=0,h=0;h=s))for(var A=d>1?(S-_)*(u-1)/(d-1):0,C=h>1?(E-k)*(c-1)/(h-1):0,M=0;M1?_*(u-1)+M*A:.5*(_+S)*(u-1);if(N<0||N>u-1)for(var T=0;T1?k*(c-1)+T*C:.5*(k+E)*(c-1))<0||H>c-1)for(I=0;I1?k*(c-1)+T*C:.5*(k+E)*(c-1))<0||H>c-1)for(I=0;I=t.size/s)throw new Error("Invalid indices: "+h+" does not index into "+t.shape);for(var v=0;v=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var y=0;y0,function(){return"scheme must not be an empty string."});var r=t.getInstance();w(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function wc(t){if(-1===t.indexOf(bc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+yc.getSchemes().join(","));return{scheme:t.split(bc)[0],path:t.split(bc)[1]}}function xc(t,e,n){return void 0===n&&(n=!1),c(this,void 0,void 0,function(){var r,i,o,a,s,u,c,f,d;return l(this,function(l){switch(l.label){case 0:return w(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),w((r=vc.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),w(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),i=r[0],w((o=vc.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),w(o.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),a=o[0],s=wc(t).scheme,u=wc(t).path,c=s===wc(t).scheme,[4,i.load()];case 1:return f=l.sent(),n&&c?[4,yc.getManager(s).removeModel(u)]:[3,3];case 2:l.sent(),l.label=3;case 3:return[4,a.save(f)];case 4:return d=l.sent(),!n||c?[3,6]:[4,yc.getManager(s).removeModel(u)];case 5:l.sent(),l.label=6;case 6:return[2,d.modelArtifactsInfo]}})})}var _c="models_store",kc="model_info_store";function Sc(){if(!h.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Ec(t){var e=t.result;e.createObjectStore(_c,{keyPath:"modelPath"}),e.createObjectStore(kc,{keyPath:"modelPath"})}var Oc=function(){function t(t){if(this.indexedDB=Sc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return c(this,void 0,void 0,function(){return l(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Ec(i)},i.onsuccess=function(){var o=i.result;if(null==e){var a=o.transaction(_c,"readonly"),s=a.objectStore(_c).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return o.close(),r(s.error)},a.oncomplete=function(){return o.close()}}else{var u,c=gc(e),l=o.transaction(kc,"readwrite"),f=l.objectStore(kc),d=f.put({modelPath:n.modelPath,modelArtifactsInfo:c});d.onsuccess=function(){var i=(u=o.transaction(_c,"readwrite")).objectStore(_c).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});i.onsuccess=function(){return t({modelArtifactsInfo:c})},i.onerror=function(t){var e=(f=l.objectStore(kc)).delete(n.modelPath);e.onsuccess=function(){return o.close(),r(i.error)},e.onerror=function(t){return o.close(),r(i.error)}}},d.onerror=function(t){return o.close(),r(d.error)},l.oncomplete=function(){null==u?o.close():u.oncomplete=function(){return o.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),Ac=function(t){return h.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Oc.URL_SCHEME)?(e=t.slice(Oc.URL_SCHEME.length),new Oc(e)):null;var e};vc.registerSaveRouter(Ac),vc.registerLoadRouter(Ac);var Cc=function(){function t(){this.indexedDB=Sc()}return t.prototype.listModels=function(){return c(this,void 0,void 0,function(){var t=this;return l(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Ec(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(kc,"readonly"),o=i.objectStore(kc).getAll();o.onsuccess=function(){for(var t={},n=0,r=o.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){w(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),w(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),w(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(o){return o.then(function(o){var a=n+ ++i/t.length*(r-n);return e(a),o}),o}))}function Kc(t,e){return c(this,void 0,void 0,function(){var n,r,i,o,a,s,u,c,f;return l(this,function(l){switch(l.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?nt:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit)}),i=0,o=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return a=l.sent(),[3,4];case 2:return[4,Gc(r,e.onProgress,i,o)];case 3:a=l.sent(),l.label=4;case 4:return s=a.map(function(t){return t.arrayBuffer()}),u=.5,c=1,null!=e.onProgress?[3,6]:[4,Promise.all(s)];case 5:return f=l.sent(),[3,8];case 6:return[4,Gc(s,e.onProgress,u,c)];case 7:f=l.sent(),l.label=8;case 8:return[2,f]}})})}function Xc(t){var e=this;return function(n,r,i){return void 0===r&&(r=""),c(e,void 0,void 0,function(){var e,o,a,s,u,c,f,d,h,p;return l(this,function(l){switch(l.label){case 0:if(e=n.map(function(){return!1}),o={},a=null!=i?i.map(function(){return!1}):[],s=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var u="quantization"in t?t.quantization.dtype:t.dtype,c=lc[u]*S(t.shape),l=function(){e[n]=!0,null==o[n]&&(o[n]=[]),o[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=i?i.forEach(function(e,n){e===t.name&&(l(),a[n]=!0)}):l(),s.push(t.name),r+=c})}),!a.every(function(t){return t}))throw u=i.filter(function(t,e){return!a[e]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),f=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=r+(r.endsWith("/")?"":"/")+t;f.push(e)})}),[4,t(f)];case 1:return d=l.sent(),h={},p=0,c.forEach(function(t){for(var e=n[t].paths.length,r=0,i=0;i0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&w(2===t.length,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return c(this,void 0,void 0,function(){var e,n,r,i;return l(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((i=o.sent()).ok)return[2,{modelArtifactsInfo:gc(t),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}})})},t.prototype.load=function(){return c(this,void 0,void 0,function(){var t,e,n,r,i,o,a,s;return l(this,function(u){switch(u.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=u.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");u.label=2;case 2:return u.trys.push([2,4,,5]),[4,t.json()];case 3:return e=u.sent(),[3,5];case 4:throw u.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,i=e.weightsManifest,null==r&&null==i)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==i?[3,7]:[4,this.loadWeights(i)];case 6:s=u.sent(),o=s[0],a=s[1],u.label=7;case 7:return[2,{modelTopology:r,weightSpecs:o,weightData:a}]}})})},t.prototype.loadWeights=function(t){return c(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u,c,f,d;return l(this,function(l){switch(l.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],i=n[1],o=this.weightPathPrefix||r,a=[],s=0,u=t;s0&&(t=u({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=u({weightData:this.weightData},t)),null!=this.trainingConfig&&(t=u({trainingConfig:this.trainingConfig},t)),[2,t]})})},t}(),el=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){return[2,this.saveHandler(t)]})})},t}(),nl=Object.freeze({browserFiles:function(t){return new $c(t)},browserHTTPRequest:function(t,e){return Qc(t,e)},concatenateArrayBuffers:pc,decodeWeights:fc,encodeWeights:function(t,e){return c(this,void 0,void 0,function(){var n,r,i,o,a,s=this;return l(this,function(u){switch(u.label){case 0:for(n=[],r=[],i=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),o=function(o){var a=i[o],u=Array.isArray(t)?t[o].tensor:t[a];if("float32"!==u.dtype&&"int32"!==u.dtype&&"bool"!==u.dtype&&"string"!==u.dtype)throw new Error("Unsupported dtype in weight '"+a+"': "+u.dtype);var f={name:a,shape:u.shape,dtype:u.dtype};if("string"===u.dtype){var d=new Promise(function(t){return c(s,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return e=f,[4,u.data()];case 1:return n=i.sent(),r=h.platform.encodeUTF8(n.join("\0")),e.byteLength=r.length,e.delimiter="\0",t(r),[2]}})})});r.push(d)}else r.push(u.data());null!=e&&(f.group=e),n.push(f)},a=0;a0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),w(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),w(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),w(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),w(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var o=or(r.asType("int32"),n),a=or(i.asType("int32"),n);return o.transpose().matMul(a).asType("int32")}}),il=Object.freeze({confusionMatrix:rl}),ol=dn({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return It.fromPixels(t,e)}}),al=Object.freeze({toPixels:function(t,e){return c(this,void 0,void 0,function(){var n,r,i,o,a,s,u,c,f,d,h,p,m,g,v,b,y,w,x,_,k,S,E;return l(this,function(l){switch(l.label){case 0:if(n=Qe(t,"img","toPixels"),t instanceof pt||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),i=r[0],o=r[1],(a=2===n.rank?1:n.shape[2])>4||2===a)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+a);return[4,n.data()];case 1:return s=l.sent(),u=n.min(),c=n.max(),[4,Promise.all([u.data(),c.data()])];case 2:if(f=l.sent(),d=f[0],h=f[1],p=d[0],m=h[0],u.dispose(),c.dispose(),"float32"===n.dtype){if(p<0||m>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+p+" - "+m+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(p<0||m>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+p+" - "+m+"].")}for(g="float32"===n.dtype?255:1,v=new Uint8ClampedArray(o*i*4),b=0;b0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),ul.register(t)}var ll=Object.freeze({Serializable:sl,SerializationMap:ul,registerClass:cl}),fl=.001,dl=.1;function hl(){return 32===It.backend.floatPrecision()?fl:dl}function pl(t,e,n){var r=!0;if((B(t)||B(e))&&(r=!1),B(t)&&B(e)&&(r=!0),r){var i=t.constructor.name,o=e.constructor.name;if(i!==o)throw new Error("Arrays are of different type. Actual: "+i+". Expected: "+o)}if(Array.isArray(t)&&Array.isArray(e)){var a=Je(t),s=Je(e);if(!E(a,s))throw new Error("Arrays have different shapes. Actual: ["+a+"]. Expected: ["+s+"]")}var u=B(t)?t:k(t),c=B(e)?e:k(e);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+".\nActual: "+u+".\nExpected: "+c+".");for(var l=0;ln)}var gl=Object.freeze({TEST_EPSILON_FLOAT16:dl,expectArraysClose:function(t,e,n){return null==n&&(n=hl()),pl(t,e,function(t,e){return ml(t,e,n)})},testEpsilon:hl,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return q(t)||q(t[0])||q(e)||q(e[0])?pl(t,n,function(t,e){return t==e}):pl(t,e,function(t,e){return ml(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=hl()),!ml(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;rn)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),vl="1.2.2",bl=Object.freeze({gpgpu_util:vo,webgl_util:Me,MathBackendWebGL:zo,setWebGLContext:Ft,GPGPUContext:bo}),yl=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),i=r.value,o=r.grads;if(null!=n){var a=n.map(function(t){return{name:t.name,tensor:o[t.name]}});this.applyGradients(a)}else this.applyGradients(o);return ze(o),e?i:(i.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return Br(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&ze(this.iterations_)},e.prototype.saveIterations=function(){return c(this,void 0,void 0,function(){return l(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:bn(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},e.prototype.extractIterations=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}})})},e}(sl);Object.defineProperty(yl,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var wl=function(t){function e(e,n,r){void 0===r&&(r=null);var i=t.call(this)||this;return i.learningRate=e,i.rho=n,i.epsilon=r,i.accumulatedGrads=[],i.accumulatedUpdates=[],null==r&&(i.epsilon=It.backend.epsilon()),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=It.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Pe(function(){return Tn(i).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Pe(function(){return Tn(i).variable(!1)})});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Pe(function(){var t=a.mul(e.rho).add(o.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(a.add(e.epsilon).sqrt()).mul(o),r=s.mul(e.rho).add(n.square().mul(1-e.rho));a.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(i);i.assign(u)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(ze(this.accumulatedGrads.map(function(t){return t.variable})),ze(this.accumulatedUpdates.map(function(t){return t.variable})))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="AdadeltaOptimizer",e}(yl);cl(wl);var xl=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=It.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Pe(function(){return An(i.shape,e.initialAccumulatorValue).variable(!1)})});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=e.accumulatedGrads[r].variable;Pe(function(){var t=a.add(o.square());a.assign(t);var n=o.div(t.add(It.backend.epsilon()).sqrt()).mul(-e.learningRate).add(i);i.assign(n)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&ze(this.accumulatedGrads.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(yl);cl(xl);var _l=function(t){function e(e,n,r,i){void 0===i&&(i=null);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=i,o.accumulatedFirstMoment=[],o.accumulatedSecondMoment=[],Pe(function(){o.accBeta1=bn(n).variable(),o.accBeta2=bn(r).variable()}),null==i&&(o.epsilon=It.backend.epsilon()),o}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Pe(function(){var r=Js(1,e.accBeta1),i=Js(1,e.accBeta2);n.forEach(function(n,o){var a=It.registeredVariables[n];null==e.accumulatedFirstMoment[o]&&(e.accumulatedFirstMoment[o]={originalName:n+"/m",variable:Pe(function(){return Tn(a).variable(!1)})}),null==e.accumulatedSecondMoment[o]&&(e.accumulatedSecondMoment[o]={originalName:n+"/v",variable:Pe(function(){return Tn(a).variable(!1)})});var s=Array.isArray(t)?t[o].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[o].variable,c=e.accumulatedSecondMoment[o].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),f=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),d=l.div(r),h=f.div(i);u.assign(l),c.assign(f);var p=d.div(h.sqrt().add(e.epsilon)).mul(-e.learningRate).add(a);a.assign(p)}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&ze(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&ze(this.accumulatedSecondMoment.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e,n=this;return l(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Pe(function(){n.accBeta1.assign(Gs(n.beta1,n.iterations_+1)),n.accBeta2.assign(Gs(n.beta2,n.iterations_+1))}),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(yl);cl(_l);var kl=function(t){function e(e,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=0);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=i,a.decay=o,a.accumulatedFirstMoment=[],a.accumulatedWeightedInfNorm=[],Pe(function(){a.iteration=bn(0).variable(),a.accBeta1=bn(n).variable()}),null==i&&(a.epsilon=It.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Pe(function(){var r=Js(1,e.accBeta1),i=Fs(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,o){var a=It.registeredVariables[n];null==e.accumulatedFirstMoment[o]&&(e.accumulatedFirstMoment[o]={originalName:n+"/m",variable:Tn(a).variable(!1)}),null==e.accumulatedWeightedInfNorm[o]&&(e.accumulatedWeightedInfNorm[o]={originalName:n+"/v",variable:Tn(a).variable(!1)});var s=Array.isArray(t)?t[o].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[o].variable,c=e.accumulatedWeightedInfNorm[o].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),f=c.mul(e.beta2),d=s.abs(),h=f.maximum(d);u.assign(l),c.assign(h);var p=i.div(r).mul(l.div(h.add(e.epsilon))).add(a);a.assign(p)}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&ze(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&ze(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(yl);cl(kl);var Sl=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var o=It.registeredVariables[n];Pe(function(){var t=e.c.mul(i).add(o);o.assign(t)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Le(bn(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(yl);cl(Sl);var El=function(t){function e(e,n,r){void 0===r&&(r=!1);var i=t.call(this,e)||this;return i.learningRate=e,i.momentum=n,i.useNesterov=r,i.accumulations=[],i.m=bn(i.momentum),i}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=It.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:Pe(function(){return Tn(i).variable(!1)})});var o=e.accumulations[r].variable,a=Array.isArray(t)?t[r].tensor:t[n];null!=a&&Pe(function(){var t,n=e.m.mul(o).add(a);t=e.useNesterov?e.c.mul(a.add(n.mul(e.m))).add(i):e.c.mul(n).add(i),o.assign(n),i.assign(t)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&ze(this.accumulations.map(function(t){return t.variable}))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="MomentumOptimizer",e}(Sl);cl(El);var Ol=function(t){function e(e,n,r,i,o){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===i&&(i=null),void 0===o&&(o=!1);var a=t.call(this)||this;return a.learningRate=e,a.decay=n,a.momentum=r,a.epsilon=i,a.accumulatedMeanSquares=[],a.accumulatedMoments=[],a.accumulatedMeanGrads=[],a.centered=o,null==i&&(a.epsilon=It.backend.epsilon()),a}return s(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=It.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Pe(function(){return Tn(i).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Pe(function(){return Tn(i).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Pe(function(){return Tn(i).variable(!1)})});var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Pe(function(){var t=a.mul(e.decay).add(o.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(o.mul(1-e.decay)),c=s.mul(e.momentum).add(o.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));a.assign(t),n.assign(u),s.assign(c);var l=i.sub(c);i.assign(l)}else{var f=a.mul(e.decay).add(o.square().mul(1-e.decay));c=s.mul(e.momentum).add(o.mul(e.learningRate).div(f.add(e.epsilon).sqrt())),a.assign(f),s.assign(c),l=i.sub(c),i.assign(l)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&ze(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&ze(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&ze(this.accumulatedMoments.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return c(this,void 0,void 0,function(){var t;return l(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return c(this,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(yl);cl(Ol);var Al=function(){function t(){}return t.sgd=function(t){return new Sl(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new El(t,e,n)},t.rmsprop=function(t,e,n,r,i){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===i&&(i=!1),new Ol(t,e,n,r,i)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new _l(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new wl(t,e,n)},t.adamax=function(t,e,n,r,i){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===i&&(i=0),new kl(t,e,n,r,i)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new xl(t,e)},t}(),Cl={sgd:Al.sgd,momentum:Al.momentum,adadelta:Al.adadelta,adagrad:Al.adagrad,rmsprop:Al.rmsprop,adamax:Al.adamax,adam:Al.adam},Ml="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:void 0!==o?o:function(t){return t()};function Nl(){return new Promise(function(t){return Ml(function(){return t()})})}dt=oc}.call(this,n(44),n(27),n(18).Buffer,n(356).setImmediate)},function(t,e,n){"use strict";var r=function(t,e,n){return t.fields=e||[],t.fname=n,t};function i(t){return null==t?null:t.fname}function o(t){return null==t?null:t.fields}var a=function(t){throw Error(t)},s=function(t){var e,n,r,i=[],o=null,s=0,u=t.length,c="";function l(){i.push(c+t.substring(e,n)),c="",e=n+1}for(t+="",e=n=0;ne&&l(),s=e=n+1):"]"===r&&(s||a("Access path missing open bracket: "+t),s>0&&l(),s=0,e=n+1):n>e?l():e=n+1}return s&&a("Access path missing closing bracket: "+t),o&&a("Access path missing closing quote: "+t),n>e&&(n++,l()),i},u=Array.isArray,c=function(t){return t===Object(t)},l=function(t){return"string"==typeof t};function f(t){return u(t)?"["+t.map(f)+"]":c(t)||l(t)?JSON.stringify(t).replace("\u2028","\\u2028").replace("\u2029","\\u2029"):t}var d=function(t,e){var n=s(t),i="return _["+n.map(f).join("][")+"];";return r(Function("_",i),[t=1===n.length?n[0]:t],e||t)},h=[],p=d("id"),m=r(function(t){return t},h,"identity"),g=r(function(){return 0},h,"zero"),v=r(function(){return 1},h,"one"),b=r(function(){return!0},h,"true"),y=r(function(){return!1},h,"false");function w(t,e,n){var r=[e].concat([].slice.call(n));console[t].apply(console,r)}var x=function(t,e){var n=t||0;return{level:function(t){return arguments.length?(n=+t,this):n},error:function(){return n>=1&&w(e||"error","ERROR",arguments),this},warn:function(){return n>=2&&w(e||"warn","WARN",arguments),this},info:function(){return n>=3&&w(e||"log","INFO",arguments),this},debug:function(){return n>=4&&w(e||"log","DEBUG",arguments),this}}},_=function(t){return t[t.length-1]},k=function(t){return null==t||""===t?null:+t};function S(t){return function(e){return t*Math.exp(e)}}function E(t){return function(e){return Math.log(t*e)}}function O(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function A(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function C(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function M(t,e,n,r){var i=n(t[0]),o=n(_(t)),a=(o-i)*e;return[r(i-a),r(o-a)]}function N(t,e){return M(t,e,k,m)}function T(t,e){var n=Math.sign(t[0]);return M(t,e,E(n),S(n))}function I(t,e,n){return M(t,e,C(n),C(1/n))}function D(t,e,n){return M(t,e,O(n),A(n))}function j(t,e,n,r,i){var o=r(t[0]),a=r(_(t)),s=null!=e?r(e):(o+a)/2;return[i(s+(o-s)*n),i(s+(a-s)*n)]}function R(t,e,n){return j(t,e,n,k,m)}function F(t,e,n){var r=Math.sign(t[0]);return j(t,e,n,E(r),S(r))}function P(t,e,n,r){return j(t,e,n,C(r),C(1/r))}function z(t,e,n,r){return j(t,e,n,O(r),A(r))}function L(t){return 1+~~(new Date(t).getMonth()/3)}function B(t){return 1+~~(new Date(t).getUTCMonth()/3)}var U=function(t){return null!=t?u(t)?t:[t]:[]},W=function(t,e,n){var r,i=t[0],o=t[1];return o=n-e?[e,n]:[i=Math.min(Math.max(i,e),n-r),i+r]},q=function(t){return"function"==typeof t},V=function(t,e){var n,i,a,u,c,l,d,h,p,m=[],g=(t=U(t)).map(function(t,e){return null==t?null:(m.push(e),q(t)?t:s(t).map(f).join("]["))}),v=m.length-1,b=U(e),y="var u,v;return ";if(v<0)return null;for(i=0;i<=v;++i)a=g[n=m[i]],q(a)?(u="(u=this."+(l="f"+n)+"(a))",c="(v=this."+l+"(b))",(d=d||{})[l]=a):(u="(u=a["+a+"])",c="(v=b["+a+"])"),l="((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))","descending"!==b[n]?(p=1,h=-1):(p=-1,h=1),y+="("+u+"<"+c+"||u==null)&&v!=null?"+h+":(u>v||v==null)&&u!=null?"+p+":"+l+"!==u&&v===v?"+h+":v!==v&&u===u?"+p+(no&&(o=r))}else{for(r=e(t[a]);null==r||r!=r;r=e(t[++a]));for(i=o=r;ao&&(o=r))}return[i,o]},X=function(t,e){var n,r,i,o,a,s=-1,u=t.length;if(null==e){for(;++s=r){n=i=r;break}for(o=a=s;++sr&&(n=r,o=s),i=r){n=i=r;break}for(o=a=s;++sr&&(n=r,o=s),ia&&(i=o,o=a,a=i),n=void 0===n||n,r=void 0===r||r,(n?o<=t:o0?n[u++]:e[s++];for(;s=0;)n+=t;return n},ft=function(t,e,n,r){var i=n||" ",o=t+"",a=e-o.length;return a<=0?o:"left"===r?lt(i,a)+o:"center"===r?lt(i,~~(a/2))+o+lt(i,Math.ceil(a/2)):o+lt(i,a)},dt=function(t){return t&&_(t)-t[0]||0},ht=function(t){return null==t||""===t?null:!(!t||"false"===t||"0"===t||!t)};function pt(t){return ot(t)?t:it(t)?t:Date.parse(t)}var mt=function(t,e){return e=e||pt,null==t||""===t?null:e(t)},gt=function(t){return null==t||""===t?null:t+""},vt=function(t){for(var e={},n=0,r=t.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]e?1:0}(t,e)}function A(t){if(null==t)return t;for(var e=[],n=0,r=t;n=0),v(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every(function(t){return typeof t===e})}function T(t,e){Array.isArray(t)?(r.util.assert(t.length>0,function(){return e+" is unexpectedly an empty array."}),t.forEach(function(t,n){return T(t,"element "+(n+1)+" of "+e)})):r.util.assert(Number.isInteger(t)&&t>0,function(){return"Expected "+e+" to be a positive integer, but got "+function t(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return t(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}(t)+"."})}function I(t,e){return Object(r.tidy)(function(){return Object(r.sqrt)(Object(r.sum)(Object(r.mulStrict)(t,t),e,!0))})}var D=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getConfig=function(){return{}},e}(r.serialization.Serializable),j=function(t){function e(e){var n=t.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return o(e,t),e.prototype.apply=function(t){var e=this;return Object(r.tidy)(function(){var n=I(t,e.axis),i=Object(r.clipByValue)(n,0,e.maxValue);return Object(r.mul)(t,Object(r.div)(i,Object(r.add)(l(),n)))})},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(D);r.serialization.registerClass(j);var R=function(t){function e(e){var n=t.call(this)||this;return n.defaultAxis=0,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return o(e,t),e.prototype.apply=function(t){var e=this;return Object(r.tidy)(function(){return Object(r.div)(t,Object(r.add)(l(),I(t,e.axis)))})},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(D);r.serialization.registerClass(R);var F=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.relu)(t)},e.className="NonNeg",e}(D);r.serialization.registerClass(F);var P=function(t){function e(e){var n=t.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=e.minValue?e.minValue:n.defaultMinValue,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.rate=null!=e.rate?e.rate:n.defaultRate,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return o(e,t),e.prototype.apply=function(t){var e=this;return Object(r.tidy)(function(){var n=I(t,e.axis),i=Object(r.add)(Object(r.mul)(e.rate,Object(r.clipByValue)(n,e.minValue,e.maxValue)),Object(r.mul)(1-e.rate,n));return Object(r.mul)(t,Object(r.div)(i,Object(r.add)(l(),n)))})},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(D);r.serialization.registerClass(P);var z={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function L(t){return S(t)}function B(t,e){return void 0===e&&(e={}),E(t,r.serialization.SerializationMap.getMap().classNameMap,e,"constraint")}function U(t){return null==t?null:"string"==typeof t?B({className:t in z?z[t]:t,config:{}}):t instanceof D?t:B(t)}var W=Object.freeze({maxNorm:function(t){return new j(t)},unitNorm:function(t){return new R(t)},nonNeg:function(){return new F},minMaxNorm:function(t){return new P(t)}}),q=["channelsFirst","channelsLast"],V=["valid","same","causal"],H=["max","avg"],$=["sum","mul","concat","ave"],G=new Map;function K(t){M(q,"DataFormat",t)}function X(t){M(V,"PaddingMode",t)}var Y=[],J="/";function Z(t,e){Y.push(t);try{var n=e();return Y.pop(),n}catch(t){throw Y.pop(),t}}function Q(t){if(!nt(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===Y.length?"":Y.join(J)+J)+t}function tt(t){if(!nt(t))throw new Error("Not a valid tensor name: '"+t+"'");G.has(t)||G.set(t,0);var e=G.get(t);if(G.set(t,G.get(t)+1),e>0){var n=t+"_"+e;return G.set(n,1),n}return t}var et=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function nt(t){return!!t.match(et)}function rt(t){return t===parseInt(t.toString(),10)}function it(t,e,n){null==e&&(e=0),null==n&&(n=t.length);for(var r=1,i=e;i= 2 but got x shape = "+t.shape+" and y shape = "+e.shape);if(e.rank>=3&&(u=t.shape.slice(-1)[0])!==(f=e.shape.slice(-2)[0]))throw new p("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+t.shape+" and y shape = "+e.shape);if(2===t.rank&&2===e.rank){var o=!1,a=!1;return r.fused.matMul(t,e,o,a,i?xt(t.rank,i,"channelsLast"):null,n)}var s=t.shape.slice(),u=s.pop();t=t.reshape([-1,u]);var c=e.shape.slice(),l=c.pop(),f=c.pop(),d=c.concat([l]),h=Array.from({length:e.rank},function(t,n){return 0===n?e.rank-2:n<=e.rank-2?n-1:n});e=e.transpose(h).reshape([f,-1]);var m=s.concat(d);return o=!1,a=!1,r.fused.matMul(t,e,o,a,i?xt(t.rank,i,"channelsLast"):null,n).reshape(m)}function yt(t,e,n){return Object(r.tidy)(function(){return e=Array.isArray(e)?Object(r.tensor1d)(e,"int32"):e.toInt(),Object(r.gather)(t,e,n)})}function wt(t){return Object(r.mulStrict)(t,t)}function xt(t,e,n){var r=e.shape;if(1!==e.rank&&e.rank!==t)throw new h("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+t);if(5===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1,1]):e.reshape([1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,1,r[0]]):e.reshape([1].concat(r))}else if(4===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1]):e.reshape([1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,r[0]]):e.reshape([1].concat(r))}else if(3===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1]):e.reshape([1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,r[0]]):e.reshape([1].concat(r))}else if(t<3)return e;throw new h("Unsupported input rank by biasAdd: "+e.rank)}function _t(t,e,n){return Object(r.tidy)(function(){return null==n&&(n="channelsLast"),K(n),t.add(xt(t.rank,e,n))})}function kt(t,e,n,i){return Object(r.tidy)(function(){return Object(r.dropout)(t,e,n,i)})}function St(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Et=["fanIn","fanOut","fanAvg"],Ot=["normal","uniform","truncatedNormal"],At=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(r.serialization.Serializable),Ct=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t,e){return Object(r.zeros)(t,e)},e.className="Zeros",e}(At);r.serialization.registerClass(Ct);var Mt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t,e){return Object(r.ones)(t,e)},e.className="Ones",e}(At);r.serialization.registerClass(Mt);var Nt=function(t){function e(e){var n=t.call(this)||this;if("object"!=typeof e)throw new h("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new h("config must have value set but got "+e);return n.value=e.value,n}return o(e,t),e.prototype.apply=function(t,e){var n=this;return Object(r.tidy)(function(){return Object(r.mul)(Object(r.scalar)(n.value),Object(r.ones)(t,e))})},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(At);r.serialization.registerClass(Nt);var Tt=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=e.minval||n.DEFAULT_MINVAL,n.maxval=e.maxval||n.DEFAULT_MAXVAL,n.seed=e.seed,n}return o(e,t),e.prototype.apply=function(t,e){return Object(r.randomUniform)(t,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(At);r.serialization.registerClass(Tt);var It=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return o(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new p("randomNormal does not support dType "+e+".");return vt(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="RandomNormal",e}(At);r.serialization.registerClass(It);var Dt=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return o(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new p("truncatedNormal does not support dType "+e+".");return Object(r.truncatedNormal)(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="TruncatedNormal",e}(At);r.serialization.registerClass(Dt);var jt=function(t){function e(e){var n=t.call(this)||this;return n.gain=null!=e.gain?e.gain:1,n}return o(e,t),e.prototype.apply=function(t,e){var n=this;return Object(r.tidy)(function(){if(2!==t.length||t[0]!==t[1])throw new h("Identity matrix initializer can only be used for 2D square matrices.");return Object(r.mul)(n.gain,Object(r.eye)(t[0]))})},e.prototype.getConfig=function(){return{gain:this.gain}},e.className="Identity",e}(At);r.serialization.registerClass(jt);var Rt=function(t){function e(e){var n=t.call(this)||this;if(e.scale<0)throw new h("scale must be a positive float. Got: "+e.scale);return n.scale=null==e.scale?1:e.scale,n.mode=null==e.mode?"fanIn":e.mode,function(t){M(Et,"FanMode",t)}(n.mode),n.distribution=null==e.distribution?"normal":e.distribution,function(t){M(Ot,"Distribution",t)}(n.distribution),n.seed=e.seed,n}return o(e,t),e.prototype.apply=function(t,e){var n=function(t,e){var n,r;if(void 0===e&&(e="channelsLast"),K(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var i=it(t,2);n=t[1]*i,r=t[0]*i}else"channelsLast"===e&&(i=it(t,0,t.length-2),n=t[t.length-2]*i,r=t[t.length-1]*i);else{var o=it(t);n=Math.sqrt(o),r=Math.sqrt(o)}return[n,r]}(t),i=n[0],o=n[1],a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,i):"fanOut"===this.mode?a/=Math.max(1,o):a/=Math.max(1,(i+o)/2),"normal"===this.distribution){var s=Math.sqrt(a);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new p(this.getClassName()+" does not support dType "+e+".");return Object(r.truncatedNormal)(t,0,s,e,this.seed)}var u=Math.sqrt(3*a);return Object(r.randomUniform)(t,-u,u,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(At);r.serialization.registerClass(Rt);var Ft=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="GlorotUniform",e}(Rt);r.serialization.registerClass(Ft);var Pt=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="GlorotNormal",e}(Rt);r.serialization.registerClass(Pt);var zt=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="HeNormal",e}(Rt);r.serialization.registerClass(zt);var Lt=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="HeUniform",e}(Rt);r.serialization.registerClass(Lt);var Bt=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="LeCunNormal",e}(Rt);r.serialization.registerClass(Bt);var Ut=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return o(e,t),e.prototype.getClassName=function(){return Rt.className},e.className="LeCunNormal",e}(Rt);r.serialization.registerClass(Ut);var Wt=function(t){function e(e){var n=t.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==e.gain?n.DEFAULT_GAIN:e.gain,n.seed=e.seed,null!=n.seed)throw new p("Random seed is not implemented for Orthogonal Initializer yet.");return n}return o(e,t),e.prototype.apply=function(t,e){var n=this;return Object(r.tidy)(function(){if(2!==t.length)throw new p("The Orthogonal Initializer does not support non-2D shapes yet.");t[0]*t[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+t[0]*t[1]+") elements: Slowness may result.");var e=vt(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32"),i=r.linalg.gramSchmidt(e);return t[0]>t[1]&&(i=i.transpose()),Object(r.mul)(n.gain,i)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(At);r.serialization.registerClass(Wt);var qt={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Vt(t,e){return void 0===e&&(e={}),E(t,r.serialization.SerializationMap.getMap().classNameMap,e,"initializer")}function Ht(t){return S(t)}function $t(t){if("string"==typeof t){var e=t in qt?qt[t]:t;if("GlorotNormal"===e)return new Pt;if("GlorotUniform"===e)return new Ft;if("HeNormal"===e)return new zt;if("HeUniform"===e)return new Lt;if("LeCunNormal"===e)return new Bt;if("LeCunUniform"===e)return new Ut;var n={};return n.className=e,n.config={},Vt(n)}return t instanceof At?t:Vt(t)}var Gt=Object.freeze({zeros:function(){return new Ct},ones:function(){return new Mt},constant:function(t){return new Nt(t)},randomUniform:function(t){return new Tt(t)},randomNormal:function(t){return new It(t)},truncatedNormal:function(t){return new Dt(t)},identity:function(t){return new jt(t)},varianceScaling:function(t){return new Rt(t)},glorotUniform:function(t){return new Ft(t)},glorotNormal:function(t){return new Pt(t)},heNormal:function(t){return new zt(t)},heUniform:function(t){return new Lt(t)},leCunNormal:function(t){return new Bt(t)},leCunUniform:function(t){return new Ut(t)},orthogonal:function(t){return new Wt(t)}}),Kt=0;function Xt(){return Kt++}var Yt={};function Jt(t){return void 0===t&&(t=""),t in Yt||(Yt[t]=0),Yt[t]+=1,t+Yt[t].toString()}function Zt(t){return Array.isArray(t)&&Array.isArray(t[0])}function Qt(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function te(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new h("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function ee(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new h("Expected exactly 1 Shape; got "+t.length)}return t}function ne(t){for(var e=0,n=0,r=t;n1)throw new f("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new f("Layer "+this.name+" is not connected, no input to return.");return y(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new f("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new f("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return y(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),e.prototype.calculateLosses=function(){return this.losses.map(function(t){return t()})},Object.defineProperty(e.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this._trainableWeights.forEach(function(e){return e.trainable=t}),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(t){return t.trainable}):[]},set:function(t){this._trainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(t){return!t.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(t){this._nonTrainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},e.prototype.assertInputCompatibility=function(t){if(t=w(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=w(this.inputSpec);if(t.length!==e.length)throw new h("Layer "+this.name+" expects "+e.length+" inputs, but it received "+t.length+" input tensors. Input received: "+t);for(var n=0;n=0?a[u]:a[a.length+u];if(null!=c&&-1===[c,null].indexOf(l))throw new h("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+c+" but got shape "+a+".")}}if(null!=i.shape)for(var f=0;f0&&Array.isArray(m[0])?m.map(function(r,i){return new ce(v,r,n,w(t),e,n.name,i)}):new ce(v,m,n,w(t),e,n.name),n.addInboundNode(t,g,null,null,h,m,e),n._refCount++,null!=n.activityRegularizer)throw new p("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g})},e.prototype.warnOnIncompatibleInputShape=function(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(t)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=t[r]&&t[r]!==n&&(e=!0)}),e&&console.warn("The shape of the input tensor ("+JSON.stringify(t)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(e.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new f("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var t=[],e=0,n=this.inboundNodes;e0?[4,Promise.all(e)]:[3,2];case 1:for(u=c.sent(),l=0;l=0&&Number.isInteger(e),function(){return"Verbosity level is expected to be an integer >= 0, but got "+e}),t.checkForDuplicate(n),null==t.constructors[e]&&(t.constructors[e]=[]),t.constructors[e].push(n)},t.checkForDuplicate=function(e){for(var n in t.constructors)t.constructors[+n].forEach(function(t){if(t===e)throw new h("Duplicate callback constructor.")})},t.clear=function(){t.constructors={}},t.createCallbacks=function(e){var n=[];for(var r in t.constructors){var i=+r;e>=i&&n.push.apply(n,t.constructors[i])}return n.map(function(t){return new t})},t.constructors={},t}();function Oe(t,e,n,r,i,o,a,s,u){var c=new _e,l=[new xe].concat(Ee.createCallbacks(e));null!=t&&l.push.apply(l,t),l.push(c);var f=new we(l);return f.setParams({epochs:n,initialEpoch:r,samples:i,steps:o,batchSize:a,verbose:e,doValidation:s,metrics:u}),{callbackList:f,history:c}}function Ae(t,e){return Object(r.tidy)(function(){"float32"!==t.dtype&&(t=t.asType("float32"));var n=Object(r.sum)(wt(t),e,!0),i=Object(r.fill)(n.shape,l()),o=Object(r.sqrt)(Object(r.maximum)(n,i));return Object(r.div)(t,o)})}function Ce(t,e){return Object(r.tidy)(function(){return Object(r.mean)(wt(Object(r.sub)(e,t)),-1)})}function Me(t,e){return Object(r.tidy)(function(){return Object(r.mean)(Object(r.abs)(Object(r.sub)(e,t)),-1)})}function Ne(t,e){return Object(r.tidy)(function(){var n=Object(r.sub)(t,e),i=Object(r.clipByValue)(Object(r.abs)(t),l(),Number.MAX_VALUE),o=Object(r.abs)(Object(r.div)(n,i));return Object(r.mul)(100,Object(r.mean)(o,-1))})}function Te(t,e,n){return void 0===n&&(n=!1),Object(r.tidy)(function(){if(n)e=Object(r.softmax)(e);else{var i=Object(r.sum)(e,e.shape.length-1,!0);e=Object(r.div)(e,i)}return e=Object(r.clipByValue)(e,l(),1-l()),Object(r.neg)(Object(r.sum)(Object(r.mul)(t.toFloat(),Object(r.log)(e)),e.shape.length-1))})}function Ie(t,e){return Object(r.tidy)(function(){var n=Object(r.floor)(function(t){var e=[it(t.shape)];return t.reshape(e)}(t)).toInt(),i=(e=Object(r.clipByValue)(e,l(),1-l())).shape;return Te(Object(r.oneHot)(n,i[i.length-1]).reshape(i),e,!1)})}function De(t,e){return Object(r.tidy)(function(){var n;return n=Object(r.clipByValue)(e,l(),1-l()),n=Object(r.log)(Object(r.div)(n,Object(r.sub)(1,n))),Object(r.mean)(function(t,e){if(!r.util.arraysEqual(t.shape,e.shape))throw new h("logits and labels must have the same shape, but got shapes "+JSON.stringify(t.shape)+" and "+JSON.stringify(e.shape));return Object(r.tidy)(function(){var n=e.relu(),r=e.abs().neg();return n.sub(e.mul(t)).add(r.exp().log1p())})}(t,n),-1)})}function je(t,e){return Object(r.tidy)(function(){var n=Ae(t,-1),i=Ae(e,-1),o=Object(r.mul)(n,i);return Object(r.neg)(Object(r.sum)(o,-1))})}var Re={meanSquaredError:Ce,meanAbsoluteError:Me,meanAbsolutePercentageError:Ne,meanSquaredLogarithmicError:function(t,e){return Object(r.tidy)(function(){var n=Object(r.clipByValue)(e,l(),Number.MAX_VALUE),i=Object(r.log)(Object(r.add)(1,n)),o=Object(r.clipByValue)(t,l(),Number.MAX_VALUE),a=Object(r.log)(Object(r.add)(1,o));return Object(r.mean)(wt(Object(r.sub)(i,a)),-1)})},squaredHinge:function(t,e){return Object(r.tidy)(function(){var n=Object(r.maximum)(0,Object(r.sub)(1,Object(r.mul)(t,e)));return Object(r.mean)(wt(n),-1)})},hinge:function(t,e){return Object(r.tidy)(function(){var n=Object(r.maximum)(0,Object(r.sub)(1,Object(r.mul)(t,e)));return Object(r.mean)(n,-1)})},categoricalHinge:function(t,e){return Object(r.tidy)(function(){var n=Object(r.sum)(Object(r.mul)(t,e),-1),i=Object(r.max)(Object(r.mul)(Object(r.sub)(1,t),e),-1);return Object(r.maximum)(0,Object(r.add)(1,Object(r.sub)(i,n)))})},logcosh:function(t,e){return Object(r.tidy)(function(){var n=Math.log(2),i=Object(r.sub)(e,t),o=Object(r.sub)(Object(r.add)(i,Object(r.softplus)(Object(r.mul)(-2,i))),n);return Object(r.mean)(o,-1)})},categoricalCrossentropy:Te,sparseCategoricalCrossentropy:Ie,binaryCrossentropy:De,kullbackLeiblerDivergence:function(t,e){return Object(r.tidy)(function(){var n=Object(r.clipByValue)(t,l(),1),i=Object(r.clipByValue)(e,l(),1);return Object(r.sum)(Object(r.mul)(t,Object(r.log)(Object(r.div)(n,i))),-1)})},poisson:function(t,e){return Object(r.tidy)(function(){var n=Object(r.log)(Object(r.add)(l(),e));return Object(r.mean)(Object(r.sub)(e,Object(r.mul)(t,n)),-1)})},cosineProximity:je};function Fe(t){if("string"==typeof t){if(t in Re)return Re[t];var e="Unknown loss "+t;throw t.toLowerCase().includes("softmaxcrossentropy")&&(e="Unknown loss "+t+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new h(e)}return t}function Pe(t,e){return Object(r.tidy)(function(){var n=Object(r.mul)(.5,Object(r.onesLike)(e)),i=ct(Object(r.greater)(e,n),t.dtype);return Object(r.mean)(Object(r.equal)(t,i),-1)})}function ze(t,e){return Object(r.tidy)(function(){return ct(Object(r.equal)(Object(r.argMax)(t,-1),Object(r.argMax)(e,-1)),"float32")})}function Le(t,e){return Object(r.tidy)(function(){return Object(r.logicalAnd)(t.equal(1),e.equal(1)).sum().cast("float32")})}function Be(t,e){return Object(r.tidy)(function(){var n=Le(t,e),i=function(t,e){return Object(r.tidy)(function(){return Object(r.logicalAnd)(t.equal(0),e.equal(1)).sum().cast("float32")})}(t,e),o=n.add(i);return Object(r.where)(Object(r.greater)(o,0),n.div(o),0).cast("float32")})}function Ue(t,e){return De(t,e)}function We(t,e){return t.rank===e.rank&&(t=t.squeeze([t.rank-1])),(e=e.argMax(-1)).dtype!==t.dtype&&(e=e.asType(t.dtype)),Object(r.equal)(t,e).asType("float32")}var qe=Te,Ve=Ie,He={binaryAccuracy:Pe,categoricalAccuracy:ze,precision:Be,categoricalCrossentropy:qe,sparseCategoricalCrossentropy:Ve,mse:Ce,MSE:Ce,mae:Me,MAE:Me,mape:Ne,MAPE:Ne,cosine:je};function $e(t,e,n){void 0===n&&(n=console.log);for(var r="",i=0;i0&&(r=r.slice(0,r.length-1)+" "),r=(r+=t[i]).slice(0,e[i]),r+=" ".repeat(e[i]-r.length);n(r)}function Ge(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}$e([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function Ke(t,e,n,r){var i;try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}for(var o=[],a=0,s=t.inboundNodes;a0&&-1===n.indexOf(u)))for(var c=0;c0,function(){return"Expected at least one fetch, got none"});var n=[],i={};if(1===t.length){var o=nn(t[0],e);n=o.sorted,i=o.recipientMap}else for(var a=new Set,s=0,u=t;si.maxNumTensors&&(i.maxNumTensors=x),x0;){var l=u[u.length-1];if(n.has(l.name))u.pop();else{var f=c[c.length-1]===u.length-1;if(0===l.inputs.length||f)u.pop(),r.push(l),n.add(l.name),f&&c.pop();else{c.push(u.length-1);for(var d=0,h=l.inputs;d0&&Number.isInteger(t),function(){return"batchSize is required to be a positive integer, but got "+t})}function ln(t,e,n){return null==t?[null]:Array.isArray(t)?t.map(function(t){return ft(t,e,n-e)}):ft(t,e,n-e)}function fn(t,e){return Object(r.tidy)(function(){return null==t?null:Array.isArray(t)?t.map(function(t){return fn(t,e)}):yt(t,"int32"===e.dtype?e:e.toInt())})}function dn(t,e){for(var n=[],r=0,i=null;r=t&&(i=t),n.push([r,i]),r=i;return n}function hn(t,e,n,i){return void 0===i&&(i={}),u(this,void 0,void 0,function(){var o,a,s,l,f,d,m,g,v,b,y,w,x,_,k,S,E,O,A;return c(this,function(C){switch(C.label){case 0:if(t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,C.label=1;case 1:if(C.trys.push([1,,3,4]),cn(m=null==i.batchSize?32:i.batchSize),g=t.standardizeUserData(e,n,!1,m),o=g[0],a=g[1],v=!1,b=void 0,null!=i.validationData&&i.validationData.length>0){if(v=!0,2!==i.validationData.length)throw 3===i.validationData.length?new p("validationData including sample weights is not supported yet."):new h("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+i.validationData+" is invalid.");s=i.validationData[0],l=i.validationData[1],y=t.standardizeUserData(s,l,!0,m),f=y[0],d=y[1],b=f.concat(d)}else null!=i.validationSplit&&i.validationSplit>0&&i.validationSplit<1?(v=!0,w=Math.floor(o[0].shape[0]*(1-i.validationSplit)),x=o[0].shape[0],f=ln(o,w,x),o=ln(o,0,w),d=ln(a,w,x),a=ln(a,0,w),b=f.concat(d)):null!=i.validationSteps&&(v=!0);return _=o.concat(a),t.checkTrainableWeightsConsistency(),k=t.makeTrainFunction(),S=t.getDedupedMetricsNames(),E=void 0,O=void 0,v?(t.makeTestFunction(),E=t.testFunction,O=S.slice().concat(S.map(function(t){return"val_"+t}))):(E=null,b=[],O=S.slice()),A=Se(i.callbacks,i.yieldEvery),[4,function(t,e,n,i,o,a,s,l,f,d,h,m,g,v,b){return u(this,void 0,void 0,function(){var u,b,y,w,x,_,k,S;return c(this,function(E){switch(E.label){case 0:return null==o&&(o=32),null==a&&(a=1),null==h&&(h=!0),null==g&&(g=0),u=!1,null!=f&&null!=d&&(u=!0),null!=(b=t.checkNumSamples(n,o,v,"steps_per_epoch"))&&(y=ut(0,b)),null==s&&(s=1),w=Oe(l,s,a,g,b,v,o,u,m),x=w.callbackList,_=w.history,x.setModel(t),t.history=_,[4,x.onTrainBegin()];case 1:E.sent(),t.stopTraining_=!1,k=function(a){var s,l,m,g,v;return c(this,function(w){switch(w.label){case 0:return[4,x.onEpochBegin(a)];case 1:return w.sent(),s={},[3,2];case 2:if("batch"===h)throw new p("batch shuffling is not implemneted yet");h&&r.util.shuffle(y),l=Object(r.tensor1d)(y),m=dn(b,o),g=function(a){var h;return c(this,function(c){switch(c.label){case 0:return h={},[4,x.onBatchBegin(a,h)];case 1:return c.sent(),Object(r.tidy)(function(){var c=m[a][0],p=m[a][1],g=ft(l,c,p-c);h.batch=a,h.size=p-c;for(var v=fn(n,g),b=e(v),y=0;y0)o=!0;else if(vn(t)){for(var a in t)if(t.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new h("Error when checking model "+i+" expected no data, but got "+t)}return[]}if(null==t)return e.map(function(t){return null});var s;if(vn(t)){t=t,s=[];for(var u=0,c=e;u1)throw new h("The model "+i+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);s=[t]}if(s=pn(s),null!=n)for(var f=0;f=0&&m!==g)throw new h("Error when checking "+i+": expected "+e[f]+" to have shape ["+n[f]+"], but got array with shape ["+d.shape+"].")}}return s}function yn(t,e,n,r,i){var o;if(void 0===r&&(r=!0),void 0===i&&(i=""),Array.isArray(t)){if(t.length!==e.length)throw new h("Error when checking model "+i+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+e.length+" Tensor(s), but instead got "+t.length+" Tensors(s).");o=t}else{if(e.length>1)throw new h("The model expects "+e.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(t.shape)+".");o=[t]}if(null!=n)for(var a=0;a1||1===s.length&&s[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,s)}if(e)for(var u=0,c=t.layers;u1&&(e.metricsTensors.push([n,t]),e.metricsNames.push(e.outputNames[t]+"_loss"))}});var g=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map(function(t){return[]});var n;if("string"==typeof t||"function"==typeof t)n=[t];else{if(!Array.isArray(t)&&"object"!=typeof t)throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: "+t);n=t}if(Array.isArray(n))return e.map(function(t){return n});for(var r=[],i=0,o=e;i1&&(n=e.outputNames[t]+"_"+n),e.metricsNames.push(n),e.metricsTensors.push([r,t])}(t,r,c)},s=0,u=g[t];s0)throw new p("Verbose mode is not implemented yet.");return r.util.assert(!i||n.batches>0&&Number.isInteger(n.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),"function"==typeof e.next?(u=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:u=g.sent(),g.label=3;case 3:s=u,l=0,f=0,d=function(){var e;return c(this,function(u){switch(u.label){case 0:return[4,s.next()];case 1:return e=u.sent(),a=Object(r.tidy)(function(){if(e.value){var n=an(t,e.value),i=Object(r.tidy)(function(){return o(n)});if(Object(r.dispose)(n),0===f)for(var s=0;s0&&Object(r.dispose)(n)};for(s=0;s0){var l=[];throw e.forEach(function(e,n){null==e&&l.push(t[n])}),new h("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(l))}return e},e.prototype.predictLoop=function(t,e,n){var i=this;return void 0===e&&(e=32),void 0===n&&(n=!1),Object(r.tidy)(function(){var o=i.checkNumSamples(t);if(n)throw new p("Verbose predictLoop() is not implemented yet.");for(var a=dn(o,e),s=i.outputs.map(function(t){return[]}),u=function(e){Object(r.tidy)(function(){var n=a[e][0],r=a[e][1],o=ln(t,n,r),s=[];if(Array.isArray(o))for(var u=0;u1)throw new h("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(t){return t.shape})));if(o.length>1)throw new h("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(i.length>0&&o.length>0&&!r.util.arraysEqual(i,o))throw new h("Input Tensors should have the same number of samples as target Tensors. Found "+i[0]+" input sample(s) and "+o[0]+" target sample(s).")}(t=bn(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=bn(e,this.feedOutputNames,o,!1,"target")),function(t,e,n){for(var r=[Ce,De,Te],i=0;i0&&t[0].shape[0]%i!=0)throw new h("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+i+". Found: "+t[0].shape[0]+" sample(s).");return[t,e,null]},e.prototype.testLoop=function(t,e,n,i,o){var a=this;return void 0===i&&(i=0),Object(r.tidy)(function(){var s=a.checkNumSamples(e,n,o,"steps"),u=[];if(i>0)throw new p("Verbose mode is not implemented yet.");if(null!=o)throw new p("steps mode in testLoop() is not implemented yet");for(var c=dn(s,n),l=Object(r.tensor1d)(ut(0,s)),f=0;f1&&(i+="_"+b(t.slice(0,n),r)),e.push(i)}return e},e.prototype.makeTrainFunction=function(){var t=this;return function(e){var n=e.slice(0,t.inputs.length),i=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),o=[],a=t.collectedTrainableWeights.map(function(t){return t.read()});return[t.optimizer_.minimize(function(){for(var e=[],a=0;a0&&Number.isInteger(n.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs}),r.util.assert(!i||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+n.batchesPerEpoch}),r.util.assert(null==n.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,c.label=1;case 1:return c.trys.push([1,,22,23]),o=null!=n.validationData,a=void 0,s=void 0,o&&(un(n.validationData)?r.util.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches}):(u=function(t){if(3===t.length)throw new p("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(n.validationData),a=u.xs,s=u.ys)),l=t.makeTrainFunction(),f=t.getDedupedMetricsNames(),d=void 0,d=o?f.slice().concat(f.map(function(t){return"val_"+t})):f.slice(),h=Se(n.callbacks,n.yieldEvery),m=null==n.verbose?1:n.verbose,g=Oe(h,m,n.epochs,null,null,function(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}(e,n),null,o,d),v=g.callbackList,b=g.history,v.setModel(t),t.history=b,[4,v.onTrainBegin()];case 2:return c.sent(),t.stopTraining_=!1,y=null==n.initialEpoch?0:n.initialEpoch,[4,e.iterator()];case 3:x=c.sent(),c.label=4;case 4:return y=n.batchesPerEpoch:E.done)?o?(T=void 0,un(n.validationData)?(I=w,[4,t.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,13]):[3,15]:[3,16];case 12:return T=I.apply(void 0,[c.sent()]),[3,14];case 13:T=w(t.evaluate(a,s,{batchSize:null==n.validationBatchSize?on:n.validationBatchSize,verbose:0})),c.label=14;case 14:for(D=0;D1)throw new h("Found more than one ("+n.length+") save handlers for URL '"+t+"'");t=n[0]}if(null==t.save)throw new h("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,r.io.encodeWeights(this.getNamedWeights(e))];case 1:return i=u.sent(),o=!1,a=null,s=this.toJSON(a,o),[2,t.save({modelTopology:s,weightData:i.data,weightSpecs:i.specs,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v1.2.2",convertedBy:null})]}})})},e.className="Model",e}(function(t){function e(n){var r=t.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var i=r.getClassName().toLowerCase();r.name=Jt(i)}if(r.supportsMasking=!1,r.trainable_=!0,Array.isArray(n.inputs)?r.inputs=n.inputs.slice():r.inputs=[n.inputs],Array.isArray(n.outputs)?r.outputs=n.outputs.slice():r.outputs=[n.outputs],A(r.inputs).length!==r.inputs.length)throw new h("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(t){return t.name}));A(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map(function(t){return t.name})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[];for(var o=0,a=r.outputs;o1 nodes"),v(0===c,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(c);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var p=0;p=0;)i.splice(i.indexOf(u),1);k.push(u)}},E=[],C=[],M=0,N=r.outputs;Mr?1:0});for(var G=0,K=$;G0)throw new h("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var t=[],e=0,n=this.layers;e0)throw new h(f.length+" of "+r+" weights are not set: "+f)}ae(c)},e.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 1.2.2",e.backend="TensorFlow.js",e},e.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=function t(e,n){if(null===e||void 0===e)return null;if("string"==typeof e)return x(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var r=[],i=e.length,o=0;o1)for(var s=0,u=a;s0){for(var h=[],p=0;p0&&t.apply(y(r),n)}function u(t){var n=t.name,o=Xe(t,null!=e.customObjects?e.customObjects:{});o.setFastWeightInitDuringBuild(r),i[n]=o,t.inboundNodes.forEach(function(t){if(!(t instanceof Array))throw new h("Corrupted configuration, expected array for nodeData: "+t);a(o,t)})}for(var c=e.name,l=e.layers,f=0,d=l;f0)&&(n=e.sourceLayer,r=e.nodeIndex),0===n.inboundNodes.length)return[e];var i=n.inboundNodes[r];if(0===i.inboundLayers.length)return i.inputTensors;for(var o=[],a=0;a1)throw new h("Found more than one ("+n.length+") load handlers for URL '"+t+"'");t=n[0]}return[2,function(t,e,n){return u(this,void 0,void 0,function(){var e,i,o,a,s,u;return c(this,function(c){switch(c.label){case 0:if(null==n&&(n={}),null==t.load)throw new h("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,t.load()];case 1:if(e=c.sent(),null!=(i=e.modelTopology).model_config&&(i=i.model_config),o=null==n.strict||n.strict,a=null!=e.weightData&&null!=e.weightSpecs&&o,s=Xe(Je(i),void 0,a),null!=e.weightData){if(null==e.weightSpecs)throw new h("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");u=r.io.decodeWeights(e.weightData,e.weightSpecs),s.loadWeights(u,o),Object(r.dispose)(u)}return[2,s]}})})}(t,0,e)]})})}(t,e)}function En(t){return me(t)}function On(t,e){Ee.registerCallbackConstructor(t,e)}r.serialization.registerClass(xn);var An=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getConfig=function(){return{}},e}(r.serialization.Serializable),Cn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=1),function(t,e){if(void 0===e&&(e=1),1!==e)throw new p("Support for alpha values other than 1 ("+e+") is not implemented yet.");return Object(r.elu)(t)}(t,e)},e.className="elu",e}(An);r.serialization.registerClass(Cn);var Mn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.selu)(t)},e.className="selu",e}(An);r.serialization.registerClass(Mn);var Nn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.relu)(t)},e.className="relu",e}(An);r.serialization.registerClass(Nn);var Tn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.tidy)(function(){return Object(r.minimum)(6,Object(r.relu)(t))})},e.className="relu6",e}(An);r.serialization.registerClass(Tn);var In=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return t},e.className="linear",e}(An);r.serialization.registerClass(In);var Dn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.sigmoid)(t)},e.className="sigmoid",e}(An);r.serialization.registerClass(Dn);var jn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return function(t){return Object(r.tidy)(function(){var e=Object(r.add)(.5,Object(r.mul)(.2,t));return Object(r.clipByValue)(e,0,1)})}(t)},e.className="hardSigmoid",e}(An);r.serialization.registerClass(jn);var Rn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.softplus)(t)},e.className="softplus",e}(An);r.serialization.registerClass(Rn);var Fn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return function(t){return Object(r.tidy)(function(){return Object(r.div)(t,Object(r.abs)(t).add(1))})}(t)},e.className="softsign",e}(An);r.serialization.registerClass(Fn);var Pn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t){return Object(r.tanh)(t)},e.className="tanh",e}(An);r.serialization.registerClass(Pn);var zn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),Object(r.softmax)(t,e)},e.className="softmax",e}(An);r.serialization.registerClass(zn);var Ln=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),Object(r.logSoftmax)(t,e)},e.className="logSoftmax",e}(An);function Bn(t){return t.getClassName()}function Un(t,e){return void 0===e&&(e={}),E(t,r.serialization.SerializationMap.getMap().classNameMap,e,"activation")}function Wn(t){var e;return null==t?Un(e={className:"linear",config:{}}):"string"==typeof t?((e={}).className=t,e.config={},Un(e)):t instanceof An?t:Un(t)}r.serialization.registerClass(Ln);var qn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e}(r.serialization.Serializable),Vn=function(t){function e(e){var n=t.call(this)||this;return n.l1=null==e||null==e.l1?.01:e.l1,n.l2=null==e||null==e.l2?.01:e.l2,n.hasL1=0!==n.l1,n.hasL2=0!==n.l2,n}return o(e,t),e.prototype.apply=function(t){var e=this;return Object(r.tidy)(function(){var n=Object(r.zeros)([1]);return e.hasL1&&(n=Object(r.add)(n,Object(r.sum)(Object(r.mul)(e.l1,Object(r.abs)(t))))),e.hasL2&&(n=Object(r.add)(n,Object(r.sum)(Object(r.mul)(e.l2,wt(t))))),n.asScalar()})},e.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},e.fromConfig=function(t,e){return new t({l1:e.l1,l2:e.l2})},e.className="L1L2",e}(qn);r.serialization.registerClass(Vn);var Hn={l1l2:"L1L2"};function $n(t){return S(t)}function Gn(t,e){return void 0===e&&(e={}),E(t,r.serialization.SerializationMap.getMap().classNameMap,e,"regularizer")}function Kn(t){return null==t?null:"string"==typeof t?Gn({className:t in Hn?Hn[t]:t,config:{}}):t instanceof qn?t:Gn(t)}var Xn=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,null!=e&&(n.maxValue=e.maxValue),n}return o(e,t),e.prototype.call=function(t,e){t=te(t);var n=Object(r.relu)(t);return null!=this.maxValue&&(n=Object(r.clipByValue)(n,0,this.maxValue)),n},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={maxValue:this.maxValue},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ReLU",e}(he);r.serialization.registerClass(Xn);var Yn=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_ALPHA=.3,null==e&&(e={}),n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return o(e,t),e.prototype.call=function(t,e){var n=te(t);return Object(r.leakyRelu)(n,this.alpha)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LeakyReLU",e}(he);r.serialization.registerClass(Yn);var Jn=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),n.supportsMasking=!0,n.alphaInitializer=$t(e.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=Kn(e.alphaRegularizer),n.alphaConstraint=U(e.alphaConstraint),null==e.sharedAxes)n.sharedAxes=null;else if(Array.isArray(e.sharedAxes))n.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new h("Expected sharedAxes to be a number or an array of numbers, but got "+e.sharedAxes);n.sharedAxes=[e.sharedAxes]}return n}return o(e,t),e.prototype.build=function(t){var e=(t=ee(t)).slice(1);if(null!=this.sharedAxes)for(var n=0,r=this.sharedAxes;n 0 but got "+JSON.stringify(t.filters))},e}(or),sr=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return o(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!N(t.kernelSize,"number",1,2))throw new h("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(ar);r.serialization.registerClass(sr);var ur=function(t){function e(n){var r=t.call(this,3,n)||this;return e.verifyArgs(n),r}return o(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&(!Array.isArray(t.kernelSize)||1!==t.kernelSize.length&&3!==t.kernelSize.length))throw new h("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv3D",e}(ar);r.serialization.registerClass(ur);var cr=function(t){function e(e){var n=t.call(this,e)||this;if(n.inputSpec=[new ue({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new h("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return o(e,t),e.prototype.build=function(t){var e;if(4!==(t=ee(t)).length)throw new h("Input should have rank 4; Received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new h("The channel dimension of the inputs should be defined. Found `None`.");var r=t[n],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new ue({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){var e=te(t);if(4!==e.shape.length)throw new h("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+e.shape.length);var i,o,a=e.shape,s=a[0];"channelsFirst"===n.dataFormat?(i=2,o=3):(i=1,o=2);var u=a[i],c=a[o],l=n.kernelSize[0],f=n.kernelSize[1],d=n.strides[0],p=n.strides[1],m=[s,rr(u,d,l,n.padding),rr(c,p,f,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(e=Object(r.transpose)(e,[0,2,3,1]));var g=Object(r.conv2dTranspose)(e,n.kernel.read(),m,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(g=Object(r.transpose)(g,[0,3,1,2])),null!=n.bias&&(g=_t(g,n.bias.read(),n.dataFormat)),null!=n.activation&&(g=n.activation.apply(g)),g})},e.prototype.computeOutputShape=function(t){var e,n,r,i=(t=ee(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var o=this.kernelSize[0],a=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return i[e]=this.filters,i[n]=rr(i[n],s,o,this.padding),i[r]=rr(i[r],u,a,this.padding),i},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(sr);r.serialization.registerClass(cr);var lr=function(t){function e(e){return t.call(this,2,e)||this}return o(e,t),e.className="SeparableConv2D",e}(function(t){function e(e,n){var r=t.call(this,e,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new h("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new h("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new h("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=$t(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Kn(n.depthwiseRegularizer),r.depthwiseConstraint=U(n.depthwiseConstraint),r.pointwiseInitializer=$t(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Kn(n.pointwiseRegularizer),r.pointwiseConstraint=U(n.pointwiseConstraint),r}return o(e,t),e.prototype.build=function(t){var e;if((t=ee(t)).length1)throw new h("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(t)+".");for(var i=null==t[0]?null:t[0].slice(1),o=1;o1){var b=ut(1,u).concat([0]);e.push(Object(r.transpose)(h,b)),l=!0}else e.push(h)}var y=n.mergeFunction(e),w=y.rank;if(l)if(null==w){var x=y.shape;g=[m=x[x.length-1]].concat(x.slice(0,x.length-1)),y=Object(r.transpose)(y.reshape([-1,m]),[1,0]).reshape(g)}else w>1&&(b=[w-1].concat(ut(0,w-1)),y=Object(r.transpose)(y,b));return y}return n.mergeFunction(t)})},e.prototype.computeOutputShape=function(t){var e;e=null==(t=t)[0]?null:t[0].slice(1);for(var n=1;n1)throw new h("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}},e.prototype.mergeFunction=function(t){var e=this;return Object(r.tidy)(function(){return pt(t,e.axis)})},e.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new h("A `Concatenate` layer should be called on a list of inputs.");for(var e=t,n=e[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,o=e.slice(1);i3||n.length>3)throw new p("Dot layer does not support tensors of 4D or higher rank yet.");var i=this.interpretAxes(e,n);if(e[i[0]]!==n[i[1]])throw new h("Dimension incompatibility: "+e[i[0]]+" !== "+n[i[1]])},e.prototype.mergeFunction=function(t){if(2!==t.length)throw new h("A `Dot` layer must be called on exactly 2 inputs, but received "+t.length+" input(s).");var e,n=t[0],i=t[1];return e=Array.isArray(this.axes)?this.axes.map(function(e,n){return Tr(e,t[n].shape.length)}):[Tr(this.axes,n.shape.length),Tr(this.axes,i.shape.length)],this.normalize&&(n=Ae(n,e[0]),i=Ae(i,e[1])),function(t,e,n){if(t.shape.length>3||e.shape.length>3)throw new p("batchDot is not implemented for tensors of 4D or higher rank yet");if(r.util.assert(t.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+t.shape.length}),r.util.assert(t.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+e.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===t.dtype||"complex64"===e.dtype)throw new p("batchDot is not implemented for complex64-type Tensors yet.");var i=t.shape.length,o=e.shape.length;null==n&&(n=[i-1,o-2]);var a=n;return Object(r.tidy)(function(){var n,r;if(i>o){n=i-o;for(var s=[],u=0;ui){for(n=o-i,s=[],u=0;u0){var f,d=[];for(u=f=i>o?i+o-3:i-1;u3||n.length>3)throw new p("Dot layer does not support tensors of 4D or higher rank yet.");var i=this.interpretAxes(e,n);e.splice(i[0],1),n.splice(i[1],1),n.splice(0,1);var o=e.concat(n);return 1===o.length&&o.push(1),o},e.prototype.computeMask=function(t,e){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dot",e}(Sr);r.serialization.registerClass(Ir);var Dr=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.stddev=e.stddev,n}return o(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){n.invokeCallHook(t,e);var r=te(t);return St(function(){return vt(r.shape,0,n.stddev).add(r)},function(){return r},e.training||!1)})},e.className="GaussianNoise",e}(he);r.serialization.registerClass(Dr);var jr=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n}return o(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){n.invokeCallHook(t,e);var r=te(t);return n.rate>0&&n.rate<1?St(function(){var t=Math.sqrt(n.rate/(1-n.rate));return r.mul(vt(r.shape,1,t))},function(){return r},e.training||!1):r})},e.className="GaussianDropout",e}(he);r.serialization.registerClass(jr);var Rr=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n.noiseShape=e.noiseShape,n}return o(e,t),e.prototype._getNoiseShape=function(t){return this.noiseShape||te(t).shape},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){if(n.rate<1&&n.rate>0){var i=n._getNoiseShape(t);return St(function(){var e=te(t),o=-1.7580993408473766,a=Object(r.greaterEqual)(Object(r.randomUniform)(i),n.rate);a=ct(a,"float32");var s=Math.pow((1-n.rate)*(1+n.rate*Math.pow(o,2)),-.5),u=-s*o*n.rate;return e.mul(a).add(a.add(-1).mul(o)).mul(s).add(u)},function(){return te(t)},e.training||!1)}return t})},e.className="AlphaDropout",e}(he);function Fr(t,e,n,i,o,a){var s;if(void 0===a&&(a=.001),2===t.rank)s=Object(r.batchNorm2d)(t,e,n,i,o,a);else if(3===t.rank)s=Object(r.batchNorm3d)(t,e,n,i,o,a);else{if(4!==t.rank)throw new p("batchNormalization is not implemented for array of rank "+t.rank+" yet");s=Object(r.batchNorm4d)(t,e,n,i,o,a)}return s}r.serialization.registerClass(Rr);var Pr=function(t){function e(e){var n=this;return null==e&&(e={}),(n=t.call(this,e)||this).supportsMasking=!0,n.axis=null==e.axis?-1:e.axis,n.momentum=null==e.momentum?.99:e.momentum,n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=$t(e.betaInitializer||"zeros"),n.gammaInitializer=$t(e.gammaInitializer||"ones"),n.movingMeanInitializer=$t(e.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=$t(e.movingVarianceInitializer||"ones"),n.betaConstraint=U(e.betaConstraint),n.gammaConstraint=U(e.gammaConstraint),n.betaRegularizer=Kn(e.betaRegularizer),n.gammaRegularizer=Kn(e.gammaRegularizer),n}return o(e,t),e.prototype.build=function(t){var e;t=ee(t);var n=this.axis>=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new h("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new ue({ndim:t.length,axes:(e={},e[n]=r,e)})];var i=[r];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){var i=null!=e.training&&e.training,o=te(t),a=o.shape,s=a.length,u=ut(0,s),c=n.axis>=0?n.axis:n.axis+s;u.splice(c,1);var l=g(1,s);l[c]=a[c];var f=u.slice();f.sort();var d=!r.util.arraysEqual(f,ut(0,s).slice(0,s-1));if(!i)return function(){if(d){var t=n.movingMean.read().reshape(l),e=n.movingVariance.read().reshape(l),r=n.center?n.beta.read().reshape(l):null,i=n.scale?n.gamma.read().reshape(l):null;return Fr(o,t,e,r,i,n.epsilon)}return Fr(o,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=function(t,e,n,i,o){return void 0===o&&(o=.001),r.util.arraysEqual(i.slice().sort(),ut(0,t.rank-1))?function(t,e,n,i,o){return void 0===o&&(o=.001),Object(r.tidy)(function(){var a=Object(r.moments)(t,i),s=a.mean,u=a.variance;return[Fr(t,s,u,n,e,o),s,u]})}(t,e,n,i,o):function(t,e,n,i,o){return void 0===o&&(o=.001),Object(r.tidy)(function(){for(var a=Object(r.moments)(t,i),s=a.mean,u=a.variance,c=[],l=0,f=ut(0,t.rank);l=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){return function(t,e,n){return Object(r.tidy)(function(){if(4!==t.rank)throw new h("temporalPadding expects input tensor to be 4-D, but received a "+t.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new h("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new h("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var i;return i="channelsFirst"===n?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],Object(r.pad)(t,i)})}(te(t),n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ZeroPadding2D",e}(he);function Lr(t,e,n,i,o,a){return Object(r.tidy)(function(){var s;K(o),M(H,"PoolMode",a),X(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==o&&(o="channelsLast"),null==a&&(a="max"),t=ir(t,o);var u="same"===i?"same":"valid";return s="max"===a?Object(r.maxPool)(t,e,n,u):Object(r.avgPool)(t,e,n,u),"channelsFirst"===o&&(s=Object(r.transpose)(s,[0,3,1,2])),s})}r.serialization.registerClass(zr);var Br=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=2),n=t.call(this,e)||this,"number"==typeof e.poolSize)n.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new h("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));n.poolSize=e.poolSize}if(T(n.poolSize,"poolSize"),null==e.strides)n.strides=n.poolSize;else if("number"==typeof e.strides)n.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new h("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));n.strides=e.strides}return T(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,X(n.padding),n.inputSpec=[new ue({ndim:3})],n}return o(e,t),e.prototype.computeOutputShape=function(t){var e=nr((t=ee(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){n.invokeCallHook(t,e),t=lt(te(t),2);var i=n.poolingFunction(te(t),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return Object(r.squeeze)(i,[2])})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(he),Ur=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return K(i),X(r),Lr(t,e,n,r,i,"max")},e.className="MaxPooling1D",e}(Br);r.serialization.registerClass(Ur);var Wr=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return K(i),X(r),Lr(t,e,n,r,i,"avg")},e.className="AveragePooling1D",e}(Br);r.serialization.registerClass(Wr);var qr=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new h("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides];return T(n.poolSize,"poolSize"),T(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,K(n.dataFormat),X(n.padding),n.inputSpec=[new ue({ndim:4})],n}return o(e,t),e.prototype.computeOutputShape=function(t){t=ee(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=nr(e,this.poolSize[0],this.padding,this.strides[0]),n=nr(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){return n.invokeCallHook(t,e),n.poolingFunction(te(t),n.poolSize,n.strides,n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(he),Vr=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return K(i),X(r),Lr(t,e,n,r,i,"max")},e.className="MaxPooling2D",e}(qr);r.serialization.registerClass(Vr);var Hr=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return K(i),X(r),Lr(t,e,n,r,i,"avg")},e.className="AveragePooling2D",e}(qr);r.serialization.registerClass(Hr);var $r=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new ue({ndim:3})],n}return o(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new p},e}(he),Gr=function(t){function e(e){return t.call(this,e||{})||this}return o(e,t),e.prototype.call=function(t,e){return Object(r.tidy)(function(){var e=te(t);return Object(r.mean)(e,1)})},e.className="GlobalAveragePooling1D",e}($r);r.serialization.registerClass(Gr);var Kr=function(t){function e(e){return t.call(this,e||{})||this}return o(e,t),e.prototype.call=function(t,e){return Object(r.tidy)(function(){var e=te(t);return Object(r.max)(e,1)})},e.className="GlobalMaxPooling1D",e}($r);r.serialization.registerClass(Kr);var Xr=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,K(n.dataFormat),n.inputSpec=[new ue({ndim:4})],n}return o(e,t),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(t,e){throw new p},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(he),Yr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){var e=te(t);return"channelsLast"===n.dataFormat?Object(r.mean)(e,[1,2]):Object(r.mean)(e,[2,3])})},e.className="GlobalAveragePooling2D",e}(Xr);r.serialization.registerClass(Yr);var Jr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){var e=te(t);return"channelsLast"===n.dataFormat?Object(r.max)(e,[1,2]):Object(r.max)(e,[2,3])})},e.className="GlobalMaxPooling2D",e}(Xr);function Zr(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new h("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=t.slice(t.length-r,t.length),t=t.slice(0,t.length-r)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function i(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=i(e),constants:n=i(n)}}function Qr(t,e,n,i,o,a,s,u){return void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===u&&(u=!1),Object(r.tidy)(function(){var c=e.shape.length;if(c<3)throw new h("Input should be at least 3D, but is "+c+"D.");var l=[1,0].concat(ut(2,c));if(e=Object(r.transpose)(e,l),null!=a)throw new p("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=o&&((o=o.asType("bool").asType("float32")).rank===c-1&&(o=Object(r.expandDims)(o,-1)),o=Object(r.transpose)(o,l)),i&&(e=Object(r.reverse)(e,0),null!=o&&(o=Object(r.reverse)(o,0)));var f,d,m=[],g=n,v=e.shape[0],b=Object(r.unstack)(e);null!=o&&(d=Object(r.unstack)(o));for(var y,w=function(e){var n=b[e],i=Object(r.tidy)(function(){return t(n,g)});if(null==o)f=i[0],g=i[1];else{var a=Object(r.tidy)(function(){var t=d[e],n=Object(r.onesLike)(t).sub(t);return{output:i[0].mul(t).addStrict(g[0].mul(n)),newStates:g.map(function(e,r){return i[1][r].mul(t).addStrict(e.mul(n))})}});f=a.output,g=a.newStates}u&&m.push(f)},x=0;x1?gt(n,[1,t]):n}):e.cell.stateSize>1?[gt(n,[1,e.cell.stateSize])]:[n]})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);var n=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:n};var r=t.prototype.getConfig.call(this);return Object.assign(e,r),e},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=Xe(e.cell,n);return new t(Object.assign(e,{cell:r}))},e.className="RNN",e}(he);r.serialization.registerClass(ti);var ei=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e}(he),ni=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,T(n.units,"units"),n.activation=Wn(null==e.activation?n.DEFAULT_ACTIVATION:e.activation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=$t(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=$t(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=$t(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Kn(e.kernelRegularizer),n.recurrentRegularizer=Kn(e.recurrentRegularizer),n.biasRegularizer=Kn(e.biasRegularizer),n.kernelConstraint=U(e.kernelConstraint),n.recurrentConstraint=U(e.recurrentConstraint),n.biasConstraint=U(e.biasConstraint),n.dropout=at([1,st([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=at([1,st([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return o(e,t),e.prototype.build=function(t){t=ee(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){if(2!==(t=t).length)throw new h("SimpleRNNCell expects 2 input Tensors, got "+t.length+".");var i=t[1];t=t[0];var o,a=null!=e.training&&e.training;01){for(var a=[],s=0;s= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var n=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),t.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(t){var e=[(t=ee(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},e.prototype.call=function(t,e){var n=this;return Object(r.tidy)(function(){return Qr(function(t,r){return[te(n.layer.call(t,e)),[]]},t=te(t),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(li);r.serialization.registerClass(fi);var di="concat",hi=function(t){function e(e){var n=t.call(this,e)||this,r=e.layer.getConfig(),i={};i.className=e.layer.getClassName(),i.config=r,n.forwardLayer=Xe(i),r.goBackwards=!0!==r.goBackwards;var o={};if(o.className=e.layer.getClassName(),o.config=r,n.backwardLayer=Xe(o),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===e.mergeMode?di:e.mergeMode,function(t){M($,"BidirectionalMergeMode",t)}(n.mergeMode),e.weights)throw new p("weights support is not implemented for Bidirectional layer yet.");return n._stateful=e.layer.stateful,n.returnSequences=e.layer.returnSequences,n.returnState=e.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=e.layer.inputSpec,n.numConstants=null,n}return o(e,t),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(t){var e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))},e.prototype.computeOutputShape=function(t){var e,n,r,i=this.forwardLayer.computeOutputShape(t);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),e=i[0]):e=i[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[e].concat(r).concat(r.slice()):y(n)},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var o=Zr(e,r,i,this.numConstants);if(e=o.inputs,r=o.initialState,i=o.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==i)return t.prototype.apply.call(this,e,n);var a=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new h("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,a.push.apply(a,r);var c=r.map(function(t){return new ue({shape:t.shape})});this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),s.push.apply(s,c)}if(null!=i)throw new p("Support for constants in Bidirectional layers is not implemented yet.");for(var l=a[0]instanceof ce,f=0,d=a;fe}var Ti=function(t){function e(e){var n=t.call(this)||this;if(null==e&&(e={}),e.restoreBestWeights)throw new p("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor=e.monitor||"val_loss",n.minDelta=Math.abs(e.minDelta||0),n.patience=e.patience||0,n.verbose=e.verbose||0,n.mode=e.mode||"auto",n.baseline=e.baseline,-1===["auto","min","max"].indexOf(n.mode)&&(console.warn("EarlyStopping mode '"+n.mode+"' is invalid. Falling back to mode 'auto'."),n.mode="auto"),"min"===n.mode?n.monitorFunc=Mi:"max"===n.mode?n.monitorFunc=Ni:-1!==n.monitor.indexOf("acc")?n.monitorFunc=Ni:n.monitorFunc=Mi,n.monitorFunc===Mi&&(n.minDelta*=-1),n}return o(e,t),e.prototype.onTrainBegin=function(t){return u(this,void 0,void 0,function(){return c(this,function(t){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Mi?1/0:-1/0,[2]})})},e.prototype.onEpochEnd=function(t,e){return u(this,void 0,void 0,function(){var n;return c(this,function(r){switch(r.label){case 0:return[4,ge(e)];case 1:return r.sent(),null==(n=this.getMonitorValue(e))?[2]:(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=t,this.model.stopTraining=!0)),[2])}})})},e.prototype.onTrainEnd=function(t){return u(this,void 0,void 0,function(){return c(this,function(t){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},e.prototype.getMonitorValue=function(t){null==t&&(t={});var e=t[this.monitor];return null==e&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(t)),e},e}(Ci),Ii={earlyStopping:function(t){return new Ti(t)}},Di=n(32),ji=n(168);n.d(e,"version",function(){return Ri}),n.d(e,"AdadeltaOptimizer",function(){return r.AdadeltaOptimizer}),n.d(e,"AdagradOptimizer",function(){return r.AdagradOptimizer}),n.d(e,"AdamOptimizer",function(){return r.AdamOptimizer}),n.d(e,"AdamaxOptimizer",function(){return r.AdamaxOptimizer}),n.d(e,"DataStorage",function(){return r.DataStorage}),n.d(e,"ENV",function(){return r.ENV}),n.d(e,"Environment",function(){return r.Environment}),n.d(e,"KernelBackend",function(){return r.KernelBackend}),n.d(e,"MomentumOptimizer",function(){return r.MomentumOptimizer}),n.d(e,"Optimizer",function(){return r.Optimizer}),n.d(e,"RMSPropOptimizer",function(){return r.RMSPropOptimizer}),n.d(e,"Rank",function(){return r.Rank}),n.d(e,"Reduction",function(){return r.Reduction}),n.d(e,"SGDOptimizer",function(){return r.SGDOptimizer}),n.d(e,"Tensor",function(){return r.Tensor}),n.d(e,"TensorBuffer",function(){return r.TensorBuffer}),n.d(e,"Variable",function(){return r.Variable}),n.d(e,"abs",function(){return r.abs}),n.d(e,"acos",function(){return r.acos}),n.d(e,"acosh",function(){return r.acosh}),n.d(e,"add",function(){return r.add}),n.d(e,"addN",function(){return r.addN}),n.d(e,"addStrict",function(){return r.addStrict}),n.d(e,"all",function(){return r.all}),n.d(e,"any",function(){return r.any}),n.d(e,"argMax",function(){return r.argMax}),n.d(e,"argMin",function(){return r.argMin}),n.d(e,"asin",function(){return r.asin}),n.d(e,"asinh",function(){return r.asinh}),n.d(e,"atan",function(){return r.atan}),n.d(e,"atan2",function(){return r.atan2}),n.d(e,"atanh",function(){return r.atanh}),n.d(e,"avgPool",function(){return r.avgPool}),n.d(e,"backend",function(){return r.backend}),n.d(e,"backend_util",function(){return r.backend_util}),n.d(e,"basicLSTMCell",function(){return r.basicLSTMCell}),n.d(e,"batchNorm",function(){return r.batchNorm}),n.d(e,"batchNorm2d",function(){return r.batchNorm2d}),n.d(e,"batchNorm3d",function(){return r.batchNorm3d}),n.d(e,"batchNorm4d",function(){return r.batchNorm4d}),n.d(e,"batchNormalization",function(){return r.batchNormalization}),n.d(e,"batchNormalization2d",function(){return r.batchNormalization2d}),n.d(e,"batchNormalization3d",function(){return r.batchNormalization3d}),n.d(e,"batchNormalization4d",function(){return r.batchNormalization4d}),n.d(e,"batchToSpaceND",function(){return r.batchToSpaceND}),n.d(e,"browser",function(){return r.browser}),n.d(e,"buffer",function(){return r.buffer}),n.d(e,"cast",function(){return r.cast}),n.d(e,"ceil",function(){return r.ceil}),n.d(e,"clipByValue",function(){return r.clipByValue}),n.d(e,"clone",function(){return r.clone}),n.d(e,"complex",function(){return r.complex}),n.d(e,"concat",function(){return r.concat}),n.d(e,"concat1d",function(){return r.concat1d}),n.d(e,"concat2d",function(){return r.concat2d}),n.d(e,"concat3d",function(){return r.concat3d}),n.d(e,"concat4d",function(){return r.concat4d}),n.d(e,"conv1d",function(){return r.conv1d}),n.d(e,"conv2d",function(){return r.conv2d}),n.d(e,"conv2dDerFilter",function(){return r.conv2dDerFilter}),n.d(e,"conv2dTranspose",function(){return r.conv2dTranspose}),n.d(e,"conv3d",function(){return r.conv3d}),n.d(e,"cos",function(){return r.cos}),n.d(e,"cosh",function(){return r.cosh}),n.d(e,"cumsum",function(){return r.cumsum}),n.d(e,"customGrad",function(){return r.customGrad}),n.d(e,"deprecationWarn",function(){return r.deprecationWarn}),n.d(e,"depthToSpace",function(){return r.depthToSpace}),n.d(e,"depthwiseConv2d",function(){return r.depthwiseConv2d}),n.d(e,"disableDeprecationWarnings",function(){return r.disableDeprecationWarnings}),n.d(e,"dispose",function(){return r.dispose}),n.d(e,"disposeVariables",function(){return r.disposeVariables}),n.d(e,"div",function(){return r.div}),n.d(e,"divStrict",function(){return r.divStrict}),n.d(e,"dot",function(){return r.dot}),n.d(e,"dropout",function(){return r.dropout}),n.d(e,"elu",function(){return r.elu}),n.d(e,"enableDebugMode",function(){return r.enableDebugMode}),n.d(e,"enableProdMode",function(){return r.enableProdMode}),n.d(e,"environment",function(){return r.environment}),n.d(e,"equal",function(){return r.equal}),n.d(e,"equalStrict",function(){return r.equalStrict}),n.d(e,"erf",function(){return r.erf}),n.d(e,"exp",function(){return r.exp}),n.d(e,"expandDims",function(){return r.expandDims}),n.d(e,"expm1",function(){return r.expm1}),n.d(e,"eye",function(){return r.eye}),n.d(e,"fft",function(){return r.fft}),n.d(e,"fill",function(){return r.fill}),n.d(e,"findBackend",function(){return r.findBackend}),n.d(e,"findBackendFactory",function(){return r.findBackendFactory}),n.d(e,"floor",function(){return r.floor}),n.d(e,"floorDiv",function(){return r.floorDiv}),n.d(e,"frame",function(){return r.frame}),n.d(e,"fused",function(){return r.fused}),n.d(e,"gather",function(){return r.gather}),n.d(e,"gatherND",function(){return r.gatherND}),n.d(e,"getBackend",function(){return r.getBackend}),n.d(e,"grad",function(){return r.grad}),n.d(e,"grads",function(){return r.grads}),n.d(e,"greater",function(){return r.greater}),n.d(e,"greaterEqual",function(){return r.greaterEqual}),n.d(e,"greaterEqualStrict",function(){return r.greaterEqualStrict}),n.d(e,"greaterStrict",function(){return r.greaterStrict}),n.d(e,"hammingWindow",function(){return r.hammingWindow}),n.d(e,"hannWindow",function(){return r.hannWindow}),n.d(e,"ifft",function(){return r.ifft}),n.d(e,"imag",function(){return r.imag}),n.d(e,"image",function(){return r.image}),n.d(e,"io",function(){return r.io}),n.d(e,"irfft",function(){return r.irfft}),n.d(e,"isFinite",function(){return r.isFinite}),n.d(e,"isInf",function(){return r.isInf}),n.d(e,"isNaN",function(){return r.isNaN}),n.d(e,"keep",function(){return r.keep}),n.d(e,"leakyRelu",function(){return r.leakyRelu}),n.d(e,"less",function(){return r.less}),n.d(e,"lessEqual",function(){return r.lessEqual}),n.d(e,"lessEqualStrict",function(){return r.lessEqualStrict}),n.d(e,"lessStrict",function(){return r.lessStrict}),n.d(e,"linalg",function(){return r.linalg}),n.d(e,"linspace",function(){return r.linspace}),n.d(e,"localResponseNormalization",function(){return r.localResponseNormalization}),n.d(e,"log",function(){return r.log}),n.d(e,"log1p",function(){return r.log1p}),n.d(e,"logSigmoid",function(){return r.logSigmoid}),n.d(e,"logSoftmax",function(){return r.logSoftmax}),n.d(e,"logSumExp",function(){return r.logSumExp}),n.d(e,"logicalAnd",function(){return r.logicalAnd}),n.d(e,"logicalNot",function(){return r.logicalNot}),n.d(e,"logicalOr",function(){return r.logicalOr}),n.d(e,"logicalXor",function(){return r.logicalXor}),n.d(e,"losses",function(){return r.losses}),n.d(e,"matMul",function(){return r.matMul}),n.d(e,"math",function(){return r.math}),n.d(e,"max",function(){return r.max}),n.d(e,"maxPool",function(){return r.maxPool}),n.d(e,"maximum",function(){return r.maximum}),n.d(e,"maximumStrict",function(){return r.maximumStrict}),n.d(e,"mean",function(){return r.mean}),n.d(e,"memory",function(){return r.memory}),n.d(e,"min",function(){return r.min}),n.d(e,"minimum",function(){return r.minimum}),n.d(e,"minimumStrict",function(){return r.minimumStrict}),n.d(e,"mod",function(){return r.mod}),n.d(e,"modStrict",function(){return r.modStrict}),n.d(e,"moments",function(){return r.moments}),n.d(e,"movingAverage",function(){return r.movingAverage}),n.d(e,"mul",function(){return r.mul}),n.d(e,"mulStrict",function(){return r.mulStrict}),n.d(e,"multiRNNCell",function(){return r.multiRNNCell}),n.d(e,"multinomial",function(){return r.multinomial}),n.d(e,"neg",function(){return r.neg}),n.d(e,"nextFrame",function(){return r.nextFrame}),n.d(e,"norm",function(){return r.norm}),n.d(e,"notEqual",function(){return r.notEqual}),n.d(e,"notEqualStrict",function(){return r.notEqualStrict}),n.d(e,"oneHot",function(){return r.oneHot}),n.d(e,"ones",function(){return r.ones}),n.d(e,"onesLike",function(){return r.onesLike}),n.d(e,"op",function(){return r.op}),n.d(e,"outerProduct",function(){return r.outerProduct}),n.d(e,"pad",function(){return r.pad}),n.d(e,"pad1d",function(){return r.pad1d}),n.d(e,"pad2d",function(){return r.pad2d}),n.d(e,"pad3d",function(){return r.pad3d}),n.d(e,"pad4d",function(){return r.pad4d}),n.d(e,"pool",function(){return r.pool}),n.d(e,"pow",function(){return r.pow}),n.d(e,"powStrict",function(){return r.powStrict}),n.d(e,"prelu",function(){return r.prelu}),n.d(e,"print",function(){return r.print}),n.d(e,"prod",function(){return r.prod}),n.d(e,"profile",function(){return r.profile}),n.d(e,"rand",function(){return r.rand}),n.d(e,"randomNormal",function(){return r.randomNormal}),n.d(e,"randomUniform",function(){return r.randomUniform}),n.d(e,"range",function(){return r.range}),n.d(e,"ready",function(){return r.ready}),n.d(e,"real",function(){return r.real}),n.d(e,"reciprocal",function(){return r.reciprocal}),n.d(e,"registerBackend",function(){return r.registerBackend}),n.d(e,"relu",function(){return r.relu}),n.d(e,"removeBackend",function(){return r.removeBackend}),n.d(e,"reshape",function(){return r.reshape}),n.d(e,"reverse",function(){return r.reverse}),n.d(e,"reverse1d",function(){return r.reverse1d}),n.d(e,"reverse2d",function(){return r.reverse2d}),n.d(e,"reverse3d",function(){return r.reverse3d}),n.d(e,"reverse4d",function(){return r.reverse4d}),n.d(e,"rfft",function(){return r.rfft}),n.d(e,"round",function(){return r.round}),n.d(e,"rsqrt",function(){return r.rsqrt}),n.d(e,"scalar",function(){return r.scalar}),n.d(e,"scatterND",function(){return r.scatterND}),n.d(e,"selu",function(){return r.selu}),n.d(e,"separableConv2d",function(){return r.separableConv2d}),n.d(e,"serialization",function(){return r.serialization}),n.d(e,"setBackend",function(){return r.setBackend}),n.d(e,"setPlatform",function(){return r.setPlatform}),n.d(e,"setdiff1dAsync",function(){return r.setdiff1dAsync}),n.d(e,"sigmoid",function(){return r.sigmoid}),n.d(e,"sign",function(){return r.sign}),n.d(e,"signal",function(){return r.signal}),n.d(e,"sin",function(){return r.sin}),n.d(e,"sinh",function(){return r.sinh}),n.d(e,"slice",function(){return r.slice}),n.d(e,"slice1d",function(){return r.slice1d}),n.d(e,"slice2d",function(){return r.slice2d}),n.d(e,"slice3d",function(){return r.slice3d}),n.d(e,"slice4d",function(){return r.slice4d}),n.d(e,"softmax",function(){return r.softmax}),n.d(e,"softplus",function(){return r.softplus}),n.d(e,"spaceToBatchND",function(){return r.spaceToBatchND}),n.d(e,"sparseToDense",function(){return r.sparseToDense}),n.d(e,"spectral",function(){return r.spectral}),n.d(e,"split",function(){return r.split}),n.d(e,"sqrt",function(){return r.sqrt}),n.d(e,"square",function(){return r.square}),n.d(e,"squaredDifference",function(){return r.squaredDifference}),n.d(e,"squaredDifferenceStrict",function(){return r.squaredDifferenceStrict}),n.d(e,"squeeze",function(){return r.squeeze}),n.d(e,"stack",function(){return r.stack}),n.d(e,"step",function(){return r.step}),n.d(e,"stridedSlice",function(){return r.stridedSlice}),n.d(e,"sub",function(){return r.sub}),n.d(e,"subStrict",function(){return r.subStrict}),n.d(e,"sum",function(){return r.sum}),n.d(e,"tan",function(){return r.tan}),n.d(e,"tanh",function(){return r.tanh}),n.d(e,"tensor",function(){return r.tensor}),n.d(e,"tensor1d",function(){return r.tensor1d}),n.d(e,"tensor2d",function(){return r.tensor2d}),n.d(e,"tensor3d",function(){return r.tensor3d}),n.d(e,"tensor4d",function(){return r.tensor4d}),n.d(e,"tensor5d",function(){return r.tensor5d}),n.d(e,"tensor6d",function(){return r.tensor6d}),n.d(e,"tensor_util",function(){return r.tensor_util}),n.d(e,"test_util",function(){return r.test_util}),n.d(e,"tidy",function(){return r.tidy}),n.d(e,"tile",function(){return r.tile}),n.d(e,"time",function(){return r.time}),n.d(e,"topk",function(){return r.topk}),n.d(e,"train",function(){return r.train}),n.d(e,"transpose",function(){return r.transpose}),n.d(e,"truncatedNormal",function(){return r.truncatedNormal}),n.d(e,"unsortedSegmentSum",function(){return r.unsortedSegmentSum}),n.d(e,"unstack",function(){return r.unstack}),n.d(e,"util",function(){return r.util}),n.d(e,"valueAndGrad",function(){return r.valueAndGrad}),n.d(e,"valueAndGrads",function(){return r.valueAndGrads}),n.d(e,"variable",function(){return r.variable}),n.d(e,"variableGrads",function(){return r.variableGrads}),n.d(e,"version_core",function(){return r.version_core}),n.d(e,"webgl",function(){return r.webgl}),n.d(e,"where",function(){return r.where}),n.d(e,"whereAsync",function(){return r.whereAsync}),n.d(e,"zeros",function(){return r.zeros}),n.d(e,"zerosLike",function(){return r.zerosLike}),n.d(e,"constraints",function(){return W}),n.d(e,"initializers",function(){return Gt}),n.d(e,"layers",function(){return Si}),n.d(e,"metrics",function(){return Ei}),n.d(e,"models",function(){return Oi}),n.d(e,"regularizers",function(){return Ai}),n.d(e,"CallbackList",function(){return we}),n.d(e,"CustomCallback",function(){return ke}),n.d(e,"History",function(){return _e}),n.d(e,"Callback",function(){return Ci}),n.d(e,"callbacks",function(){return Ii}),n.d(e,"EarlyStopping",function(){return Ti}),n.d(e,"InputSpec",function(){return ue}),n.d(e,"SymbolicTensor",function(){return ce}),n.d(e,"LayersModel",function(){return wn}),n.d(e,"input",function(){return En}),n.d(e,"loadLayersModel",function(){return Sn}),n.d(e,"model",function(){return _n}),n.d(e,"registerCallbackConstructor",function(){return On}),n.d(e,"sequential",function(){return kn}),n.d(e,"RNN",function(){return ti}),n.d(e,"Sequential",function(){return xn}),n.d(e,"LayerVariable",function(){return ie}),n.d(e,"version_layers",function(){return"1.2.2"}),n.d(e,"GraphModel",function(){return Di.a}),n.d(e,"loadGraphModel",function(){return Di.c}),n.d(e,"deregisterOp",function(){return Di.b}),n.d(e,"registerOp",function(){return Di.d}),n.d(e,"version_converter",function(){return Di.e}),n.d(e,"data",function(){return ji});var Ri={"tfjs-core":r.version_core,"tfjs-data":ji.version_data,"tfjs-layers":"1.2.2","tfjs-converter":Di.e,tfjs:"1.2.2"}},function(t,e,n){var r=n(8),i=n(51),o=n(35),a=n(34),s=n(50),u=function(t,e,n){var c,l,f,d,h=t&u.F,p=t&u.G,m=t&u.S,g=t&u.P,v=t&u.B,b=p?r:m?r[e]||(r[e]={}):(r[e]||{}).prototype,y=p?i:i[e]||(i[e]={}),w=y.prototype||(y.prototype={});for(c in p&&(n=e),n)f=((l=!h&&b&&void 0!==b[c])?b:n)[c],d=v&&l?s(f,r):g&&"function"==typeof f?s(Function.call,f):f,b&&a(b,c,f,t&u.U),y[c]!=f&&o(y,c,d),g&&w[c]!=f&&(w[c]=f)};r.core=i,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e,n){"use strict";n.d(e,"c",function(){return i}),n.d(e,"a",function(){return o}),n.d(e,"b",function(){return a}),n.d(e,"d",function(){return s}); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +var r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var o=function(){return(o=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0?i(r(t),9007199254740991):0}},function(t,e,n){"use strict";e.__esModule=!0;var r=a(n(495)),i=a(n(493)),o="function"==typeof i.default&&"symbol"==typeof r.default?function(t){return typeof t}:function(t){return t&&"function"==typeof i.default&&t.constructor===i.default&&t!==i.default.prototype?"symbol":typeof t};function a(t){return t&&t.__esModule?t:{default:t}}e.default="function"==typeof i.default&&"symbol"===o(r.default)?function(t){return void 0===t?"undefined":o(t)}:function(t){return t&&"function"==typeof i.default&&t.constructor===i.default&&t!==i.default.prototype?"symbol":void 0===t?"undefined":o(t)}},function(t,e,n){"use strict";(function(t){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +var r=n(759),i=n(758),o=n(357);function a(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(t,e){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|t}function p(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(t).length;default:if(r)return B(t).length;e=(""+e).toLowerCase(),r=!0}}function m(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function g(t,e,n,r,i){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(i)return-1;n=t.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof e&&(e=u.from(e,r)),u.isBuffer(e))return 0===e.length?-1:v(t,e,n,r,i);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):v(t,[e],n,r,i);throw new TypeError("val must be string, number or Buffer")}function v(t,e,n,r,i){var o,a=1,s=t.length,u=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;a=2,s/=2,u/=2,n/=2}function c(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}if(i){var l=-1;for(o=n;os&&(n=s-u),o=n;o>=0;o--){for(var f=!0,d=0;di&&(r=i):r=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a>8,i=n%256,o.push(i),o.push(r);return o}(e,t.length-n),t,n,r)}function S(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function E(t,e,n){n=Math.min(t.length,n);for(var r=[],i=e;i239?4:c>223?3:c>191?2:1;if(i+f<=n)switch(f){case 1:c<128&&(l=c);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=t[i+1],a=t[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=t[i+1],a=t[i+2],s=t[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),i+=f}return function(t){var e=t.length;if(e<=O)return String.fromCharCode.apply(String,t);for(var n="",r=0;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return M(this,e,n);case"utf8":case"utf-8":return E(this,e,n);case"ascii":return A(this,e,n);case"latin1":case"binary":return C(this,e,n);case"base64":return S(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}.apply(this,arguments)},u.prototype.equals=function(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u.compare(this,t)},u.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},u.prototype.compare=function(t,e,n,r,i){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),e<0||n>t.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&e>=n)return 0;if(r>=i)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,r>>>=0,i>>>=0,this===t)return 0;for(var o=i-r,a=n-e,s=Math.min(o,a),c=this.slice(r,i),l=t.slice(e,n),f=0;fi)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return b(this,t,e,n);case"utf8":case"utf-8":return y(this,t,e,n);case"ascii":return w(this,t,e,n);case"latin1":case"binary":return x(this,t,e,n);case"base64":return _(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function A(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;ir)&&(n=r);for(var i="",o=e;on)throw new RangeError("Trying to access beyond buffer length")}function I(t,e,n,r,i,o){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function D(t,e,n,r){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-n,2);i>>8*(r?i:1-i)}function j(t,e,n,r){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-n,4);i>>8*(r?i:3-i)&255}function R(t,e,n,r,i,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function F(t,e,n,r,o){return o||R(t,0,n,4),i.write(t,e,n,r,23,4),n+4}function P(t,e,n,r,o){return o||R(t,0,n,8),i.write(t,e,n,r,52,8),n+8}u.prototype.slice=function(t,e){var n,r=this.length;if(t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e0&&(i*=256);)r+=this[t+--e]*i;return r},u.prototype.readUInt8=function(t,e){return e||T(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||T(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||T(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||T(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||T(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||T(t,e,this.length);for(var r=this[t],i=1,o=0;++o=(i*=128)&&(r-=Math.pow(2,8*e)),r},u.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||T(t,e,this.length);for(var r=e,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},u.prototype.readInt8=function(t,e){return e||T(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||T(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(t,e){e||T(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(t,e){return e||T(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||T(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||T(t,4,this.length),i.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||T(t,4,this.length),i.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||T(t,8,this.length),i.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||T(t,8,this.length),i.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,n,r){t=+t,e|=0,n|=0,r||I(this,t,e,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+n},u.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):D(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):D(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):j(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):j(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);I(this,t,e,n,i-1,-i)}var o=0,a=1,s=0;for(this[e]=255&t;++o>0)-s&255;return e+n},u.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);I(this,t,e,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[e+o]=255&t;--o>=0&&(a*=256);)t<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(t/a>>0)-s&255;return e+n},u.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):D(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):D(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):j(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||I(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):j(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,n){return F(this,t,e,!0,n)},u.prototype.writeFloatBE=function(t,e,n){return F(this,t,e,!1,n)},u.prototype.writeDoubleLE=function(t,e,n){return P(this,t,e,!0,n)},u.prototype.writeDoubleBE=function(t,e,n){return P(this,t,e,!1,n)},u.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e=0;--i)t[i+e]=this[i+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&n<57344){if(!i){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(e-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function U(t){return r.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(z,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function W(t,e,n,r){for(var i=0;i=e.length||i>=t.length);++i)e[i+n]=t[i];return i}}).call(this,n(27))},function(t,e){var n=t.exports={version:"2.6.1"};"number"==typeof __e&&(__e=n)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return e&&t.then(function(t){return e(void 0,t),t}).catch(function(t){return e(t),t}),t}},function(t,e,n){var r=n(5),i=n(395),o=n(60),a=Object.defineProperty;e.f=n(22)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return a(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){t.exports=!n(13)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){"use strict";n.r(e);var r=function(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]},i=function(t){return(t=r(Math.abs(t)))?t[1]:NaN},o=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function a(t){if(!(e=o.exec(t)))throw new Error("invalid format: "+t);var e;return new s({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function s(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}a.prototype=s.prototype,s.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var u,c,l,f,d=function(t){t:for(var e,n=t.length,r=1,i=-1;r0){if(!+t[r])break t;i=0}}return i>0?t.slice(0,i)+t.slice(e+1):t},h=function(t,e){var n=r(t,e);if(!n)return t+"";var i=n[0],o=n[1];return o<0?"0."+new Array(-o).join("0")+i:i.length>o+1?i.slice(0,o+1)+"."+i.slice(o+1):i+new Array(o-i.length+2).join("0")},p={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:function(t){return Math.round(t).toString(10)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return h(100*t,e)},r:h,s:function(t,e){var n=r(t,e);if(!n)return t+"";var i=n[0],o=n[1],a=o-(u=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,s=i.length;return a===s?i:a>s?i+new Array(a-s+1).join("0"):a>0?i.slice(0,a)+"."+i.slice(a):"0."+new Array(1-a).join("0")+r(t,Math.max(0,e+a-1))[0]},X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}},m=function(t){return t},g=Array.prototype.map,v=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"],b=function(t){var e=void 0===t.grouping||void 0===t.thousands?m:function(t,e){return function(n,r){for(var i=n.length,o=[],a=0,s=t[0],u=0;i>0&&s>0&&(u+s+1>r&&(s=Math.max(1,r-u)),o.push(n.substring(i-=s,i+s)),!((u+=s+1)>r));)s=t[a=(a+1)%t.length];return o.reverse().join(e)}}(g.call(t.grouping,Number),t.thousands+""),n=void 0===t.currency?"":t.currency[0]+"",r=void 0===t.currency?"":t.currency[1]+"",o=void 0===t.decimal?".":t.decimal+"",s=void 0===t.numerals?m:function(t){return function(e){return e.replace(/[0-9]/g,function(e){return t[+e]})}}(g.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",l=void 0===t.minus?"-":t.minus+"",f=void 0===t.nan?"NaN":t.nan+"";function h(t){var i=(t=a(t)).fill,h=t.align,m=t.sign,g=t.symbol,b=t.zero,y=t.width,w=t.comma,x=t.precision,_=t.trim,k=t.type;"n"===k?(w=!0,k="g"):p[k]||(void 0===x&&(x=12),_=!0,k="g"),(b||"0"===i&&"="===h)&&(b=!0,i="0",h="=");var S="$"===g?n:"#"===g&&/[boxX]/.test(k)?"0"+k.toLowerCase():"",E="$"===g?r:/[%p]/.test(k)?c:"",O=p[k],A=/[defgprs%]/.test(k);function C(t){var n,r,a,c=S,p=E;if("c"===k)p=O(t)+p,t="";else{var g=(t=+t)<0;if(t=isNaN(t)?f:O(Math.abs(t),x),_&&(t=d(t)),g&&0==+t&&(g=!1),c=(g?"("===m?m:l:"-"===m||"("===m?"":m)+c,p=("s"===k?v[8+u/3]:"")+p+(g&&"("===m?")":""),A)for(n=-1,r=t.length;++n(a=t.charCodeAt(n))||a>57){p=(46===a?o+t.slice(n+1):t.slice(n))+p,t=t.slice(0,n);break}}w&&!b&&(t=e(t,1/0));var C=c.length+t.length+p.length,M=C>1)+c+t+p+M.slice(C);break;default:t=M+c+t+p}return s(t)}return x=void 0===x?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x)),C.toString=function(){return t+""},C}return{format:h,formatPrefix:function(t,e){var n=h(((t=a(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(i(e)/3))),o=Math.pow(10,-r),s=v[8+r/3];return function(t){return n(o*t)+s}}}};function y(t){return c=b(t),l=c.format,f=c.formatPrefix,c}y({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});var w=function(t){return Math.max(0,-i(Math.abs(t)))},x=function(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(i(e)/3)))-i(Math.abs(t)))},_=function(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,i(e)-i(t))+1};n.d(e,"formatDefaultLocale",function(){return y}),n.d(e,"format",function(){return l}),n.d(e,"formatPrefix",function(){return f}),n.d(e,"formatLocale",function(){return b}),n.d(e,"formatSpecifier",function(){return a}),n.d(e,"FormatSpecifier",function(){return s}),n.d(e,"precisionFixed",function(){return w}),n.d(e,"precisionPrefix",function(){return x}),n.d(e,"precisionRound",function(){return _})},function(t,e,n){(function(t){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function i(t,e){t.super_=e;var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}function o(t,e,n){if(o.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==e&&"be"!==e||(n=e,e=10),this._init(t||0,e||10,n||"be"))}var a;"object"==typeof t?t.exports=o:e.BN=o,o.BN=o,o.wordSize=26;try{a=n(722).Buffer}catch(t){}function s(t,e,n){for(var r=0,i=Math.min(t.length,n),o=e;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return r}function u(t,e,n,r){for(var i=0,o=Math.min(t.length,n),a=e;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(t){return t instanceof o||null!==t&&"object"==typeof t&&t.constructor.wordSize===o.wordSize&&Array.isArray(t.words)},o.max=function(t,e){return t.cmp(e)>0?t:e},o.min=function(t,e){return t.cmp(e)<0?t:e},o.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},o.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},o.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=6)i=s(t,n,n+6),this.words[r]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,r++);n+6!==e&&(i=s(t,e,n+6),this.words[r]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(t,e,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=e)r++;r--,i=i/e|0;for(var o=t.length-n,a=o%r,s=Math.min(o,o-a)+n,c=0,l=n;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(t,e,n){n.negative=e.negative^t.negative;var r=t.length+e.length|0;n.length=r,r=r-1|0;var i=0|t.words[0],o=0|e.words[0],a=i*o,s=67108863&a,u=a/67108864|0;n.words[0]=s;for(var c=1;c>>26,f=67108863&u,d=Math.min(c,e.length-1),h=Math.max(0,c-t.length+1);h<=d;h++){var p=c-h|0;l+=(a=(i=0|t.words[p])*(o=0|e.words[h])+f)/67108864|0,f=67108863&a}n.words[c]=0|f,u=0|l}return 0!==u?n.words[c]=0|u:n.length--,n.strip()}o.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+n:u+n,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var d=l[t],h=f[t];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var m=p.modn(h).toString(t);n=(p=p.idivn(h)).isZero()?m+n:c[d-m.length]+m+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(t,e){return r(void 0!==a),this.toArrayLike(a,t,e)},o.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},o.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===e,c=new t(o),l=this.clone();if(u){for(s=0;!l.isZero();s++)a=l.andln(255),l.iushrn(8),c[s]=a;for(;s=4096&&(n+=13,e>>>=13),e>=64&&(n+=7,e>>>=7),e>=8&&(n+=4,e>>>=4),e>=2&&(n+=2,e>>>=2),n+e},o.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,n=0;return 0==(8191&e)&&(n+=13,e>>>=13),0==(127&e)&&(n+=7,e>>>=7),0==(15&e)&&(n+=4,e>>>=4),0==(3&e)&&(n+=2,e>>>=2),0==(1&e)&&n++,n},o.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},o.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},o.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var n=0;nt.length?this.clone().iand(t):t.clone().iand(this)},o.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},o.prototype.iuxor=function(t){var e,n;this.length>t.length?(e=this,n=t):(e=t,n=this);for(var r=0;rt.length?this.clone().ixor(t):t.clone().ixor(this)},o.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},o.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},o.prototype.notn=function(t){return this.clone().inotn(t)},o.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(n=this,r=t):(n=t,r=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},o.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var n,r,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=t):(n=t,r=this);for(var o=0,a=0;a>26,this.words[a]=67108863&e;for(;0!==o&&a>26,this.words[a]=67108863&e;if(0===o&&a>>13,h=0|a[1],p=8191&h,m=h>>>13,g=0|a[2],v=8191&g,b=g>>>13,y=0|a[3],w=8191&y,x=y>>>13,_=0|a[4],k=8191&_,S=_>>>13,E=0|a[5],O=8191&E,A=E>>>13,C=0|a[6],M=8191&C,N=C>>>13,T=0|a[7],I=8191&T,D=T>>>13,j=0|a[8],R=8191&j,F=j>>>13,P=0|a[9],z=8191&P,L=P>>>13,B=0|s[0],U=8191&B,W=B>>>13,q=0|s[1],V=8191&q,H=q>>>13,$=0|s[2],G=8191&$,K=$>>>13,X=0|s[3],Y=8191&X,J=X>>>13,Z=0|s[4],Q=8191&Z,tt=Z>>>13,et=0|s[5],nt=8191&et,rt=et>>>13,it=0|s[6],ot=8191&it,at=it>>>13,st=0|s[7],ut=8191&st,ct=st>>>13,lt=0|s[8],ft=8191<,dt=lt>>>13,ht=0|s[9],pt=8191&ht,mt=ht>>>13;n.negative=t.negative^e.negative,n.length=19;var gt=(c+(r=Math.imul(f,U))|0)+((8191&(i=(i=Math.imul(f,W))+Math.imul(d,U)|0))<<13)|0;c=((o=Math.imul(d,W))+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,r=Math.imul(p,U),i=(i=Math.imul(p,W))+Math.imul(m,U)|0,o=Math.imul(m,W);var vt=(c+(r=r+Math.imul(f,V)|0)|0)+((8191&(i=(i=i+Math.imul(f,H)|0)+Math.imul(d,V)|0))<<13)|0;c=((o=o+Math.imul(d,H)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,r=Math.imul(v,U),i=(i=Math.imul(v,W))+Math.imul(b,U)|0,o=Math.imul(b,W),r=r+Math.imul(p,V)|0,i=(i=i+Math.imul(p,H)|0)+Math.imul(m,V)|0,o=o+Math.imul(m,H)|0;var bt=(c+(r=r+Math.imul(f,G)|0)|0)+((8191&(i=(i=i+Math.imul(f,K)|0)+Math.imul(d,G)|0))<<13)|0;c=((o=o+Math.imul(d,K)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,r=Math.imul(w,U),i=(i=Math.imul(w,W))+Math.imul(x,U)|0,o=Math.imul(x,W),r=r+Math.imul(v,V)|0,i=(i=i+Math.imul(v,H)|0)+Math.imul(b,V)|0,o=o+Math.imul(b,H)|0,r=r+Math.imul(p,G)|0,i=(i=i+Math.imul(p,K)|0)+Math.imul(m,G)|0,o=o+Math.imul(m,K)|0;var yt=(c+(r=r+Math.imul(f,Y)|0)|0)+((8191&(i=(i=i+Math.imul(f,J)|0)+Math.imul(d,Y)|0))<<13)|0;c=((o=o+Math.imul(d,J)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,r=Math.imul(k,U),i=(i=Math.imul(k,W))+Math.imul(S,U)|0,o=Math.imul(S,W),r=r+Math.imul(w,V)|0,i=(i=i+Math.imul(w,H)|0)+Math.imul(x,V)|0,o=o+Math.imul(x,H)|0,r=r+Math.imul(v,G)|0,i=(i=i+Math.imul(v,K)|0)+Math.imul(b,G)|0,o=o+Math.imul(b,K)|0,r=r+Math.imul(p,Y)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0;var wt=(c+(r=r+Math.imul(f,Q)|0)|0)+((8191&(i=(i=i+Math.imul(f,tt)|0)+Math.imul(d,Q)|0))<<13)|0;c=((o=o+Math.imul(d,tt)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,r=Math.imul(O,U),i=(i=Math.imul(O,W))+Math.imul(A,U)|0,o=Math.imul(A,W),r=r+Math.imul(k,V)|0,i=(i=i+Math.imul(k,H)|0)+Math.imul(S,V)|0,o=o+Math.imul(S,H)|0,r=r+Math.imul(w,G)|0,i=(i=i+Math.imul(w,K)|0)+Math.imul(x,G)|0,o=o+Math.imul(x,K)|0,r=r+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(b,Y)|0,o=o+Math.imul(b,J)|0,r=r+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0;var xt=(c+(r=r+Math.imul(f,nt)|0)|0)+((8191&(i=(i=i+Math.imul(f,rt)|0)+Math.imul(d,nt)|0))<<13)|0;c=((o=o+Math.imul(d,rt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,r=Math.imul(M,U),i=(i=Math.imul(M,W))+Math.imul(N,U)|0,o=Math.imul(N,W),r=r+Math.imul(O,V)|0,i=(i=i+Math.imul(O,H)|0)+Math.imul(A,V)|0,o=o+Math.imul(A,H)|0,r=r+Math.imul(k,G)|0,i=(i=i+Math.imul(k,K)|0)+Math.imul(S,G)|0,o=o+Math.imul(S,K)|0,r=r+Math.imul(w,Y)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,r=r+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,tt)|0,r=r+Math.imul(p,nt)|0,i=(i=i+Math.imul(p,rt)|0)+Math.imul(m,nt)|0,o=o+Math.imul(m,rt)|0;var _t=(c+(r=r+Math.imul(f,ot)|0)|0)+((8191&(i=(i=i+Math.imul(f,at)|0)+Math.imul(d,ot)|0))<<13)|0;c=((o=o+Math.imul(d,at)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,r=Math.imul(I,U),i=(i=Math.imul(I,W))+Math.imul(D,U)|0,o=Math.imul(D,W),r=r+Math.imul(M,V)|0,i=(i=i+Math.imul(M,H)|0)+Math.imul(N,V)|0,o=o+Math.imul(N,H)|0,r=r+Math.imul(O,G)|0,i=(i=i+Math.imul(O,K)|0)+Math.imul(A,G)|0,o=o+Math.imul(A,K)|0,r=r+Math.imul(k,Y)|0,i=(i=i+Math.imul(k,J)|0)+Math.imul(S,Y)|0,o=o+Math.imul(S,J)|0,r=r+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,tt)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,tt)|0,r=r+Math.imul(v,nt)|0,i=(i=i+Math.imul(v,rt)|0)+Math.imul(b,nt)|0,o=o+Math.imul(b,rt)|0,r=r+Math.imul(p,ot)|0,i=(i=i+Math.imul(p,at)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,at)|0;var kt=(c+(r=r+Math.imul(f,ut)|0)|0)+((8191&(i=(i=i+Math.imul(f,ct)|0)+Math.imul(d,ut)|0))<<13)|0;c=((o=o+Math.imul(d,ct)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,r=Math.imul(R,U),i=(i=Math.imul(R,W))+Math.imul(F,U)|0,o=Math.imul(F,W),r=r+Math.imul(I,V)|0,i=(i=i+Math.imul(I,H)|0)+Math.imul(D,V)|0,o=o+Math.imul(D,H)|0,r=r+Math.imul(M,G)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(N,G)|0,o=o+Math.imul(N,K)|0,r=r+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,r=r+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,tt)|0)+Math.imul(S,Q)|0,o=o+Math.imul(S,tt)|0,r=r+Math.imul(w,nt)|0,i=(i=i+Math.imul(w,rt)|0)+Math.imul(x,nt)|0,o=o+Math.imul(x,rt)|0,r=r+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,at)|0)+Math.imul(b,ot)|0,o=o+Math.imul(b,at)|0,r=r+Math.imul(p,ut)|0,i=(i=i+Math.imul(p,ct)|0)+Math.imul(m,ut)|0,o=o+Math.imul(m,ct)|0;var St=(c+(r=r+Math.imul(f,ft)|0)|0)+((8191&(i=(i=i+Math.imul(f,dt)|0)+Math.imul(d,ft)|0))<<13)|0;c=((o=o+Math.imul(d,dt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,r=Math.imul(z,U),i=(i=Math.imul(z,W))+Math.imul(L,U)|0,o=Math.imul(L,W),r=r+Math.imul(R,V)|0,i=(i=i+Math.imul(R,H)|0)+Math.imul(F,V)|0,o=o+Math.imul(F,H)|0,r=r+Math.imul(I,G)|0,i=(i=i+Math.imul(I,K)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,K)|0,r=r+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,r=r+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,r=r+Math.imul(k,nt)|0,i=(i=i+Math.imul(k,rt)|0)+Math.imul(S,nt)|0,o=o+Math.imul(S,rt)|0,r=r+Math.imul(w,ot)|0,i=(i=i+Math.imul(w,at)|0)+Math.imul(x,ot)|0,o=o+Math.imul(x,at)|0,r=r+Math.imul(v,ut)|0,i=(i=i+Math.imul(v,ct)|0)+Math.imul(b,ut)|0,o=o+Math.imul(b,ct)|0,r=r+Math.imul(p,ft)|0,i=(i=i+Math.imul(p,dt)|0)+Math.imul(m,ft)|0,o=o+Math.imul(m,dt)|0;var Et=(c+(r=r+Math.imul(f,pt)|0)|0)+((8191&(i=(i=i+Math.imul(f,mt)|0)+Math.imul(d,pt)|0))<<13)|0;c=((o=o+Math.imul(d,mt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,r=Math.imul(z,V),i=(i=Math.imul(z,H))+Math.imul(L,V)|0,o=Math.imul(L,H),r=r+Math.imul(R,G)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(F,G)|0,o=o+Math.imul(F,K)|0,r=r+Math.imul(I,Y)|0,i=(i=i+Math.imul(I,J)|0)+Math.imul(D,Y)|0,o=o+Math.imul(D,J)|0,r=r+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,r=r+Math.imul(O,nt)|0,i=(i=i+Math.imul(O,rt)|0)+Math.imul(A,nt)|0,o=o+Math.imul(A,rt)|0,r=r+Math.imul(k,ot)|0,i=(i=i+Math.imul(k,at)|0)+Math.imul(S,ot)|0,o=o+Math.imul(S,at)|0,r=r+Math.imul(w,ut)|0,i=(i=i+Math.imul(w,ct)|0)+Math.imul(x,ut)|0,o=o+Math.imul(x,ct)|0,r=r+Math.imul(v,ft)|0,i=(i=i+Math.imul(v,dt)|0)+Math.imul(b,ft)|0,o=o+Math.imul(b,dt)|0;var Ot=(c+(r=r+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,mt)|0)+Math.imul(m,pt)|0))<<13)|0;c=((o=o+Math.imul(m,mt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,r=Math.imul(z,G),i=(i=Math.imul(z,K))+Math.imul(L,G)|0,o=Math.imul(L,K),r=r+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(F,Y)|0,o=o+Math.imul(F,J)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,tt)|0)+Math.imul(D,Q)|0,o=o+Math.imul(D,tt)|0,r=r+Math.imul(M,nt)|0,i=(i=i+Math.imul(M,rt)|0)+Math.imul(N,nt)|0,o=o+Math.imul(N,rt)|0,r=r+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,at)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,at)|0,r=r+Math.imul(k,ut)|0,i=(i=i+Math.imul(k,ct)|0)+Math.imul(S,ut)|0,o=o+Math.imul(S,ct)|0,r=r+Math.imul(w,ft)|0,i=(i=i+Math.imul(w,dt)|0)+Math.imul(x,ft)|0,o=o+Math.imul(x,dt)|0;var At=(c+(r=r+Math.imul(v,pt)|0)|0)+((8191&(i=(i=i+Math.imul(v,mt)|0)+Math.imul(b,pt)|0))<<13)|0;c=((o=o+Math.imul(b,mt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,r=Math.imul(z,Y),i=(i=Math.imul(z,J))+Math.imul(L,Y)|0,o=Math.imul(L,J),r=r+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(F,Q)|0,o=o+Math.imul(F,tt)|0,r=r+Math.imul(I,nt)|0,i=(i=i+Math.imul(I,rt)|0)+Math.imul(D,nt)|0,o=o+Math.imul(D,rt)|0,r=r+Math.imul(M,ot)|0,i=(i=i+Math.imul(M,at)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,at)|0,r=r+Math.imul(O,ut)|0,i=(i=i+Math.imul(O,ct)|0)+Math.imul(A,ut)|0,o=o+Math.imul(A,ct)|0,r=r+Math.imul(k,ft)|0,i=(i=i+Math.imul(k,dt)|0)+Math.imul(S,ft)|0,o=o+Math.imul(S,dt)|0;var Ct=(c+(r=r+Math.imul(w,pt)|0)|0)+((8191&(i=(i=i+Math.imul(w,mt)|0)+Math.imul(x,pt)|0))<<13)|0;c=((o=o+Math.imul(x,mt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,r=Math.imul(z,Q),i=(i=Math.imul(z,tt))+Math.imul(L,Q)|0,o=Math.imul(L,tt),r=r+Math.imul(R,nt)|0,i=(i=i+Math.imul(R,rt)|0)+Math.imul(F,nt)|0,o=o+Math.imul(F,rt)|0,r=r+Math.imul(I,ot)|0,i=(i=i+Math.imul(I,at)|0)+Math.imul(D,ot)|0,o=o+Math.imul(D,at)|0,r=r+Math.imul(M,ut)|0,i=(i=i+Math.imul(M,ct)|0)+Math.imul(N,ut)|0,o=o+Math.imul(N,ct)|0,r=r+Math.imul(O,ft)|0,i=(i=i+Math.imul(O,dt)|0)+Math.imul(A,ft)|0,o=o+Math.imul(A,dt)|0;var Mt=(c+(r=r+Math.imul(k,pt)|0)|0)+((8191&(i=(i=i+Math.imul(k,mt)|0)+Math.imul(S,pt)|0))<<13)|0;c=((o=o+Math.imul(S,mt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,r=Math.imul(z,nt),i=(i=Math.imul(z,rt))+Math.imul(L,nt)|0,o=Math.imul(L,rt),r=r+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,at)|0)+Math.imul(F,ot)|0,o=o+Math.imul(F,at)|0,r=r+Math.imul(I,ut)|0,i=(i=i+Math.imul(I,ct)|0)+Math.imul(D,ut)|0,o=o+Math.imul(D,ct)|0,r=r+Math.imul(M,ft)|0,i=(i=i+Math.imul(M,dt)|0)+Math.imul(N,ft)|0,o=o+Math.imul(N,dt)|0;var Nt=(c+(r=r+Math.imul(O,pt)|0)|0)+((8191&(i=(i=i+Math.imul(O,mt)|0)+Math.imul(A,pt)|0))<<13)|0;c=((o=o+Math.imul(A,mt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,r=Math.imul(z,ot),i=(i=Math.imul(z,at))+Math.imul(L,ot)|0,o=Math.imul(L,at),r=r+Math.imul(R,ut)|0,i=(i=i+Math.imul(R,ct)|0)+Math.imul(F,ut)|0,o=o+Math.imul(F,ct)|0,r=r+Math.imul(I,ft)|0,i=(i=i+Math.imul(I,dt)|0)+Math.imul(D,ft)|0,o=o+Math.imul(D,dt)|0;var Tt=(c+(r=r+Math.imul(M,pt)|0)|0)+((8191&(i=(i=i+Math.imul(M,mt)|0)+Math.imul(N,pt)|0))<<13)|0;c=((o=o+Math.imul(N,mt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,r=Math.imul(z,ut),i=(i=Math.imul(z,ct))+Math.imul(L,ut)|0,o=Math.imul(L,ct),r=r+Math.imul(R,ft)|0,i=(i=i+Math.imul(R,dt)|0)+Math.imul(F,ft)|0,o=o+Math.imul(F,dt)|0;var It=(c+(r=r+Math.imul(I,pt)|0)|0)+((8191&(i=(i=i+Math.imul(I,mt)|0)+Math.imul(D,pt)|0))<<13)|0;c=((o=o+Math.imul(D,mt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,r=Math.imul(z,ft),i=(i=Math.imul(z,dt))+Math.imul(L,ft)|0,o=Math.imul(L,dt);var Dt=(c+(r=r+Math.imul(R,pt)|0)|0)+((8191&(i=(i=i+Math.imul(R,mt)|0)+Math.imul(F,pt)|0))<<13)|0;c=((o=o+Math.imul(F,mt)|0)+(i>>>13)|0)+(Dt>>>26)|0,Dt&=67108863;var jt=(c+(r=Math.imul(z,pt))|0)+((8191&(i=(i=Math.imul(z,mt))+Math.imul(L,pt)|0))<<13)|0;return c=((o=Math.imul(L,mt))+(i>>>13)|0)+(jt>>>26)|0,jt&=67108863,u[0]=gt,u[1]=vt,u[2]=bt,u[3]=yt,u[4]=wt,u[5]=xt,u[6]=_t,u[7]=kt,u[8]=St,u[9]=Et,u[10]=Ot,u[11]=At,u[12]=Ct,u[13]=Mt,u[14]=Nt,u[15]=Tt,u[16]=It,u[17]=Dt,u[18]=jt,0!==c&&(u[19]=c,n.length++),n};function p(t,e,n){return(new m).mulp(t,e,n)}function m(t,e){this.x=t,this.y=e}Math.imul||(h=d),o.prototype.mulTo=function(t,e){var n=this.length+t.length;return 10===this.length&&10===t.length?h(this,t,e):n<63?d(this,t,e):n<1024?function(t,e,n){n.negative=e.negative^t.negative,n.length=t.length+e.length;for(var r=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}n.words[o]=s,r=a,a=i}return 0!==r?n.words[o]=r:n.length--,n.strip()}(this,t,e):p(this,t,e)},m.prototype.makeRBT=function(t){for(var e=new Array(t),n=o.prototype._countBits(t)-1,r=0;r>=1;return r},m.prototype.permute=function(t,e,n,r,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,n[2*a+1]=8191&o,o>>>=13;for(a=2*e;a>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},o.prototype.muln=function(t){return this.clone().imuln(t)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),n=0;n>>i}return e}(t);if(0===e.length)return new o(1);for(var n=this,r=0;r=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var a=0;for(e=0;e>>26-n}a&&(this.words[e]=a,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,a=Math.min((t-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==l||c>=i);c--){var f=0|this.words[c];this.words[c]=l<<26-o|f>>>o,l=f&s}return u&&0!==l&&(u.words[u.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},o.prototype.shln=function(t){return this.clone().ishln(t)},o.prototype.ushln=function(t){return this.clone().iushln(t)},o.prototype.shrn=function(t){return this.clone().ishrn(t)},o.prototype.ushrn=function(t){return this.clone().iushrn(t)},o.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},o.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(u/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(t,e){var n=(this.length,t.length),r=this.clone(),i=t,a=0|i.words[i.length-1];0!=(n=26-this._countBits(a))&&(i=i.ushln(n),r.iushln(n),a=0|i.words[i.length-1]);var s,u=r.length-i.length;if("mod"!==e){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;f--){var d=67108864*(0|r.words[i.length+f])+(0|r.words[i.length+f-1]);for(d=Math.min(d/a|0,67108863),r._ishlnsubmul(i,d,f);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(i,1,f),r.isZero()||(r.negative^=1);s&&(s.words[f]=d)}return s&&s.strip(),r.strip(),"div"!==e&&0!==n&&r.iushrn(n),{div:s||null,mod:r}},o.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(i=s.div.neg()),"div"!==e&&(a=s.mod.neg(),n&&0!==a.negative&&a.iadd(t)),{div:i,mod:a}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(a=s.mod.neg(),n&&0!==a.negative&&a.isub(t)),{div:s.div,mod:a}):t.length>this.length||this.cmp(t)<0?{div:new o(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new o(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new o(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,a,s},o.prototype.div=function(t){return this.divmod(t,"div",!1).div},o.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},o.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},o.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var n=0!==e.div.negative?e.mod.isub(t):e.mod,r=t.ushrn(1),i=t.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},o.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},o.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},o.prototype.divn=function(t){return this.clone().idivn(t)},o.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++c;for(var l=n.clone(),f=e.clone();!e.isZero();){for(var d=0,h=1;0==(e.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(e.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(l),a.isub(f)),i.iushrn(1),a.iushrn(1);for(var p=0,m=1;0==(n.words[0]&m)&&p<26;++p,m<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(l),u.isub(f)),s.iushrn(1),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),i.isub(s),a.isub(u)):(n.isub(e),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:n.iushln(c)}},o.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,a=new o(1),s=new o(0),u=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var c=0,l=1;0==(e.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(e.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var f=0,d=1;0==(n.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(n.iushrn(f);f-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(s)):(n.isub(e),s.isub(a))}return(i=0===e.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(t),i},o.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),n=t.clone();e.negative=0,n.negative=0;for(var r=0;e.isEven()&&n.isEven();r++)e.iushrn(1),n.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=e.cmp(n);if(i<0){var o=e;e=n,n=o}else if(0===i||0===n.cmpn(1))break;e.isub(n)}return n.iushln(r)},o.prototype.invm=function(t){return this.egcd(t).a.umod(t)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(t){return this.words[0]&t},o.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;n--){var r=0|this.words[n],i=0|t.words[n];if(r!==i){ri&&(e=1);break}}return e},o.prototype.gtn=function(t){return 1===this.cmpn(t)},o.prototype.gt=function(t){return 1===this.cmp(t)},o.prototype.gten=function(t){return this.cmpn(t)>=0},o.prototype.gte=function(t){return this.cmp(t)>=0},o.prototype.ltn=function(t){return-1===this.cmpn(t)},o.prototype.lt=function(t){return-1===this.cmp(t)},o.prototype.lten=function(t){return this.cmpn(t)<=0},o.prototype.lte=function(t){return this.cmp(t)<=0},o.prototype.eqn=function(t){return 0===this.cmpn(t)},o.prototype.eq=function(t){return 0===this.cmp(t)},o.red=function(t){return new _(t)},o.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},o.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(t){return this.red=t,this},o.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},o.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},o.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},o.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},o.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},o.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},o.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},o.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},o.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new o(e,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function x(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=o._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function k(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v.prototype._tmp=function(){var t=new o(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,n=t;do{this.split(n,this.tmp),e=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(e>this.n);var r=e0?n.isub(this.p):n.strip(),n},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},i(b,v),b.prototype.split=function(t,e){for(var n=Math.min(t.length,9),r=0;r>>22,i=o}i>>>=22,t.words[r-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},b.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,n=0;n>>=26,t.words[n]=i,e=r}return 0!==e&&(t.words[t.length++]=e),t},o._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new b;else if("p224"===t)e=new y;else if("p192"===t)e=new w;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new x}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var n=t.add(e);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var n=t.iadd(e);return n.cmp(this.m)>=0&&n.isub(this.m),n},_.prototype.sub=function(t,e){this._verify2(t,e);var n=t.sub(e);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var n=t.isub(e);return n.cmpn(0)<0&&n.iadd(this.m),n},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new o(1)).iushrn(2);return this.pow(t,n)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);r(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,c).cmp(u);)l.redIAdd(u);for(var f=this.pow(l,i),d=this.pow(t,i.addn(1).iushrn(1)),h=this.pow(t,i),p=a;0!==h.cmp(s);){for(var m=h,g=0;0!==m.cmp(s);g++)m=m.redSqr();r(g=0;r--){for(var c=e.words[r],l=u-1;l>=0;l--){var f=c>>l&1;i!==n[0]&&(i=this.sqr(i)),0!==f||0!==a?(a<<=1,a|=f,(4==++s||0===r&&0===l)&&(i=this.mul(i,n[a]),s=0,a=0)):s=0}u=26}return i},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},o.mont=function(t){return new k(t)},i(k,_),k.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},k.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},k.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var n=t.imul(e),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},k.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new o(0)._forceRed(this);var n=t.mul(e),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},k.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)}).call(this,n(146)(t))},function(t,e,n){var r=n(59);t.exports=function(t){return Object(r(t))}},function(t,e,n){var r=n(29),i=n(19),o=n(64),a=n(68),s=n(77),u=function(t,e,n){var c,l,f,d=t&u.F,h=t&u.G,p=t&u.S,m=t&u.P,g=t&u.B,v=t&u.W,b=h?i:i[e]||(i[e]={}),y=b.prototype,w=h?r:p?r[e]:(r[e]||{}).prototype;for(c in h&&(n=e),n)(l=!d&&w&&void 0!==w[c])&&s(b,c)||(f=l?w[c]:n[c],b[c]=h&&"function"!=typeof w[c]?n[c]:g&&l?o(f,r):v&&w[c]==f?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(f):m&&"function"==typeof f?o(Function.call,f):f,m&&((b.virtual||(b.virtual={}))[c]=f,t&u.R&&y&&!y[c]&&a(y,c,f)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){var r=n(220)("wks"),i=n(151),o=n(29).Symbol,a="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=a&&o[t]||(a?o:i)("Symbol."+t))}).store=r},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){"use strict";var r=e;r.version=n(716).version,r.utils=n(715),r.rand=n(333),r.curve=n(145),r.curves=n(710),r.ec=n(702),r.eddsa=n(698)},function(t,e,n){"use strict";(function(t){n.d(e,"a",function(){return xt}),n.d(e,"c",function(){return _t}),n.d(e,"b",function(){return d}),n.d(e,"d",function(){return l}),n.d(e,"e",function(){return kt});var r,i,o=n(0),a=function(){return(a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map(function(t){return e.read(t)})},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach(function(t,r){return n.write(t,e[r])})},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n=this.maxSize)throw new Error("Max index must be < array size ("+n+" vs. "+this.maxSize+")");this.writeMany(t,Object(o.unstack)(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,i=t.map(function(t){return r+=t});if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var a=0===r?0:e.size/r,s=[];Object(o.tidy)(function(){e=e.reshape([1,r,a]);for(var u=0;u1)for(var y=1;y1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}();function ht(t,e,n){for(var r=new Set,i=[],o=null,a=null,s=new Set,u=e.slice();u.length>0;){var c=u.pop();(gt(c)||vt(c))&&null==o&&(a=(o=c).children.map(function(t){return t.name}).filter(function(t){return r.has(t)})),r.add(c.name),null==n[c.name]&&null==t[c.name]&&(0!==c.inputs.length?c.inputs.forEach(function(t){s.has(t.name)||(s.add(t.name),u.push(t))}):i.push(c.name))}return{inputs:t,outputs:e,usedNodes:r,missingInputs:i,dynamicNode:o,syncInputs:a}}var pt=["Switch","Merge","Enter","Exit","NextIteration"],mt=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function gt(t){return pt.indexOf(t.op)>=0}function vt(t){return mt.indexOf(t.op)>=0}var bt=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=t.placeholders,this._outputs=t.outputs}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map(function(e){return t[e].map(function(t){return t.id})});this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.placeholders.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.outputs.map(function(t){return t.name})},enumerable:!0,configurable:!0}),t.prototype.getCompilationKey=function(t,e){var n=t.map(function(t){return t.name}).sort(),r=e.map(function(t){return t.name}).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},t.prototype.compile=function(t,e){var n=ht(t,e,this.weightMap),r=n.missingInputs,i=n.dynamicNode,o=n.syncInputs;if(null!=i)throw new Error("This execution contains the node '"+i.name+"', which has the dynamic op '"+i.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+o+"]");if(r.length>0){var a=e.map(function(t){return t.name}),s=Object.keys(t);throw new Error("Cannot compute the outputs ["+a+"] from the provided inputs ["+s+"]. Missing the following inputs: ["+r+"]")}return function(t,e,n){var r=n.usedNodes,i=n.inputs,o=[];Object.keys(i).map(function(e){return t.nodes[e]}).forEach(function(t){r.has(t.name)&&o.push(t)}),t.weights.forEach(function(t){r.has(t.name)&&o.push(t)});for(var a=new Set,s=[];o.length>0;){var u=o.pop();a.add(u.name),e[u.name]||s.push(u),u.children.forEach(function(t){!a.has(t.name)&&r.has(t.name)&&t.inputs.every(function(t){return a.has(t.name)})&&o.push(t)})}return s}(this.graph,this.weightMap,n)},t.prototype.execute=function(t,e){var n=this,r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),this.checkOutputs(e);var i=r.map(function(t){return n.graph.nodes[t]}),s=e.map(function(t){return n.graph.nodes[v(t)[0]]}),u=this.getCompilationKey(i,s),c=this.compiledMap.get(u);null==c&&(c=this.compile(t,s),this.compiledMap.set(u,c));var l={};return Object(o.tidy)(function(){var r=new dt(n._weightMap,l),i=a({},n.weightMap);Object.keys(t).forEach(function(e){i[e]=[t[e]]});for(var o=n.getFrozenTensorIds(i),s={},u=0;u0?(w=this.processStack(i,h,e,m,y,b,n,g,c),[4,Promise.all(w)]):[3,3];case 2:return u.sent(),[3,1];case 3:if(null==f&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(x=o.filter(function(t){return!gt(t)&&!p(t.name,m,e)}).map(function(t){return t.name})).length>0)throw _="",null!=f&&(_="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+d+"]"),new Error("Cannot compute the outputs ["+x+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+l+"]. "+_);return[2,m]}})})},t.prototype.processStack=function(t,e,n,r,i,o,a,s,u){for(var c=this,l=[],f=function(){var f=e.pop();n.currentContext=f.contexts;var p="";if("Enter"===f.node.op&&h("isConstant",f.node,r,n)&&(p=m(f.node.name,n)[0]),-1===t.indexOf(f.node)){var g=ft(f.node,r,n);p||(p=m(f.node.name,n)[0]);var v=n.currentContext;g instanceof Promise?l.push(g.then(function(t){return r[p]=t,n.currentContext=v,c.checkTensorForDisposal(p,f.node,r,n,o,a,s),c.processChildNodes(f.node,e,n,r,i,u),t})):(r[p]=g,d.checkTensorForDisposal(p,f.node,r,n,o,a,s),d.processChildNodes(f.node,e,n,r,i,u))}else d.processChildNodes(f.node,e,n,r,i,u)},d=this;e.length>0;)f();return l},t.prototype.processChildNodes=function(t,e,n,r,i,o){t.children.forEach(function(t){var a=m(t.name,n)[0];!i[a]&&o.has(t.name)&&("Merge"===t.op?t.inputNames.some(function(t){return!!p(t,r,n)})&&(i[a]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every(function(t){return!!p(t,r,n)})&&(i[a]=!0,e.push({contexts:n.currentContext,node:t})))})},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(t){return t.dispose()})})},t.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach(function(n){var r=t[n],i=e.graph.nodes[n];if(i.attrParams.shape&&i.attrParams.shape.value){var a=i.attrParams.shape.value,s=a.length===r.shape.length&&r.shape.every(function(t,e){return-1===a[e]||a[e]===t});o.util.assert(s,function(){return"The shape of dict['"+i.name+"'] provided in model.execute(dict) must be ["+a+"], but was ["+r.shape+"]"})}i.attrParams.dtype&&i.attrParams.dtype.value&&o.util.assert(r.dtype===i.attrParams.dtype.value,function(){return"The dtype of dict['"+i.name+"'] provided in model.execute(dict) must be "+i.attrParams.dtype.value+", but was "+r.dtype})})},t.prototype.checkInputs=function(t){var e=this,n=Object.keys(t).filter(function(t){return!e.graph.nodes[t]});if(n.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+n+"] that are not part of graph")},t.prototype.checkOutputs=function(t){var e=this;t.forEach(function(t){var n=v(t)[0];if(!e.graph.nodes[n])throw new Error("The output '"+t+"' is not found in the graph")})},t}(),yt="?tfjs-format=file",wt="model.json",xt=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=o.io.browserHTTPRequest(t,this.loadOptions);else{var e=o.io.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(o.io.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return s(this,void 0,void 0,function(){var t,e,n;return u(this,function(r){switch(r.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=r.sent(),e=t.modelTopology,this.version=e.versions.producer+"."+e.versions.minConsumer,n=o.io.decodeWeights(t.weightData,t.weightSpecs),this.executor=new bt(R.Instance.transformGraph(e)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),[2,!0]}})})},t.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},t.prototype.normalizeInputs=function(t){if(!(t instanceof o.Tensor||Array.isArray(t)))return t;if((t=Array.isArray(t)?t:[t]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce(function(e,n,r){return e[n]=t[r],e},{})},t.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},t.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var n=this.executor.execute(t,e);return n.length>1?n:n[0]},t.prototype.executeAsync=function(t,e){return s(this,void 0,void 0,function(){var n;return u(this,function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return[2,(n=r.sent()).length>1?n:n[0]]}})})},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,n){return e[n]=[t[n]],e},{})},t.prototype.dispose=function(){this.executor.dispose()},t}();function _t(t,e){return void 0===e&&(e={}),s(this,void 0,void 0,function(){var n;return u(this,function(r){switch(r.label){case 0:if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==e&&(e={}),e.fromTFHub&&null==t.load&&(t.endsWith("/")||(t+="/"),t=""+t+wt+yt),[4,(n=new xt(t,e)).load()];case 1:return r.sent(),[2,n]}})})}var kt="1.2.2"}).call(this,n(18).Buffer)},function(t,e,n){var r=n(3),i=n(13),o=n(59),a=/"/g,s=function(t,e,n,r){var i=String(o(t)),s="<"+e;return""!==n&&(s+=" "+n+'="'+String(r).replace(a,""")+'"'),s+">"+i+""};t.exports=function(t,e){var n={};n[t]=e(s),r(r.P+r.F*i(function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}),"String",n)}},function(t,e,n){var r=n(8),i=n(35),o=n(42),a=n(87)("src"),s=Function.toString,u=(""+s).split("toString");n(51).inspectSource=function(t){return s.call(t)},(t.exports=function(t,e,n,s){var c="function"==typeof n;c&&(o(n,"name")||i(n,"name",e)),t[e]!==n&&(c&&(o(n,a)||i(n,a,t[e]?""+t[e]:u.join(String(e)))),t===r?t[e]=n:s?t[e]?t[e]=n:i(t,e,n):(delete t[e],i(t,e,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[a]||s.call(this)})},function(t,e,n){var r=n(21),i=n(88);t.exports=n(22)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){t.exports={default:n(510),__esModule:!0}},function(t,e){var n=Array.isArray;t.exports=n},function(t,e){function n(t,e){if(!t)throw new Error(e||"Assertion failed")}t.exports=n,n.equal=function(t,e,n){if(t!=e)throw new Error(n||"Assertion failed: "+t+" != "+e)}},function(t,e,n){var r=n(42),i=n(25),o=n(251)("IE_PROTO"),a=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?a:null}},function(t,e,n){var r=n(130),i=n(88),o=n(41),a=n(60),s=n(42),u=n(395),c=Object.getOwnPropertyDescriptor;e.f=n(22)?c:function(t,e){if(t=o(t),e=a(e,!0),u)try{return c(t,e)}catch(t){}if(s(t,e))return i(!r.f.call(t,e),t[e])}},function(t,e,n){var r=n(131),i=n(59);t.exports=function(t){return r(i(t))}},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){"use strict";var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const i=n(318),o=n(317);e.getDrawArea=function(t){if(t instanceof HTMLElement)return t;if(i.isSurface(t))return t.drawArea;if(i.isSurfaceInfo(t))return o.visor().surface({name:t.name,tab:t.tab,styles:t.styles}).drawArea;throw new Error("Not a drawable")},e.shallowEquals=function(t,e){const n=Object.getOwnPropertyNames(t),r=Object.getOwnPropertyNames(e);if(n.length!==r.length)return!1;for(let r=0;rrequestAnimationFrame(t))})}},function(t,e){var n,r,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(t){r=a}}();var u,c=[],l=!1,f=-1;function d(){l&&u&&(l=!1,u.length?c=u.concat(c):f=-1,c.length&&h())}function h(){if(!l){var t=s(d);l=!0;for(var e=c.length;e;){for(u=c,c=[];++f1)for(var n=1;n0?r:n)(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(30);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e){var n=t.exports={version:"2.6.1"};"number"==typeof __e&&(__e=n)},function(t,e,n){t.exports={default:n(486),__esModule:!0}},function(t,e,n){var r=n(308),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},function(t,e,n){"use strict";var r=n(38),i=n(6);function o(t,e){return 55296==(64512&t.charCodeAt(e))&&!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1))}function a(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function s(t){return 1===t.length?"0"+t:t}function u(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}e.inherits=i,e.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var n=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,n[r++]=63&a|128):o(t,i)?(a=65536+((1023&a)<<10)+(1023&t.charCodeAt(++i)),n[r++]=a>>18|240,n[r++]=a>>12&63|128,n[r++]=a>>6&63|128,n[r++]=63&a|128):(n[r++]=a>>12|224,n[r++]=a>>6&63|128,n[r++]=63&a|128)}else for(i=0;i>>0}return a},e.split32=function(t,e){for(var n=new Array(4*t.length),r=0,i=0;r>>24,n[i+1]=o>>>16&255,n[i+2]=o>>>8&255,n[i+3]=255&o):(n[i+3]=o>>>24,n[i+2]=o>>>16&255,n[i+1]=o>>>8&255,n[i]=255&o)}return n},e.rotr32=function(t,e){return t>>>e|t<<32-e},e.rotl32=function(t,e){return t<>>32-e},e.sum32=function(t,e){return t+e>>>0},e.sum32_3=function(t,e,n){return t+e+n>>>0},e.sum32_4=function(t,e,n,r){return t+e+n+r>>>0},e.sum32_5=function(t,e,n,r,i){return t+e+n+r+i>>>0},e.sum64=function(t,e,n,r){var i=t[e],o=r+t[e+1]>>>0,a=(o>>0,t[e+1]=o},e.sum64_hi=function(t,e,n,r){return(e+r>>>0>>0},e.sum64_lo=function(t,e,n,r){return e+r>>>0},e.sum64_4_hi=function(t,e,n,r,i,o,a,s){var u=0,c=e;return u+=(c=c+r>>>0)>>0)>>0)>>0},e.sum64_4_lo=function(t,e,n,r,i,o,a,s){return e+r+o+s>>>0},e.sum64_5_hi=function(t,e,n,r,i,o,a,s,u,c){var l=0,f=e;return l+=(f=f+r>>>0)>>0)>>0)>>0)>>0},e.sum64_5_lo=function(t,e,n,r,i,o,a,s,u,c){return e+r+o+s+c>>>0},e.rotr64_hi=function(t,e,n){return(e<<32-n|t>>>n)>>>0},e.rotr64_lo=function(t,e,n){return(t<<32-n|e>>>n)>>>0},e.shr64_hi=function(t,e,n){return t>>>n},e.shr64_lo=function(t,e,n){return(t<<32-n|e>>>n)>>>0}},function(t,e,n){t.exports=!n(78)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(45);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){var r=n(50),i=n(131),o=n(25),a=n(16),s=n(235);t.exports=function(t,e){var n=1==t,u=2==t,c=3==t,l=4==t,f=6==t,d=5==t||f,h=e||s;return function(e,s,p){for(var m,g,v=o(e),b=i(v),y=r(s,p,3),w=a(b.length),x=0,_=n?h(e,w):u?h(e,0):void 0;w>x;x++)if((d||x in b)&&(g=y(m=b[x],x,v),t))if(n)_[x]=g;else if(g)switch(t){case 3:return!0;case 5:return m;case 6:return x;case 2:_.push(m)}else if(l)return!1;return f?-1:c||l?l:_}}},function(t,e,n){var r=n(3),i=n(51),o=n(13);t.exports=function(t,e){var n=(i.Object||{})[t]||Object[t],a={};a[t]=e(n),r(r.S+r.F*o(function(){n(1)}),"Object",a)}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(14);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){t.exports={default:n(467),__esModule:!0}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.imgToPixelArray=e.flipImage=e.isInstanceOfSupportedElement=e.imgToTensor=e.cropImage=e.processVideo=e.array3DToImage=void 0;var r=u(n(52)),i=u(n(17)),o=u(n(72)),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(n(2)),s=u(n(108));function u(t){return t&&t.__esModule?t:{default:t}}var c=function(t){var e=Math.min(t.shape[0],t.shape[1]),n=t.shape[0]/2-e/2,r=t.shape[1]/2-e/2;return t.slice([n,r,0],[e,e,3])};e.array3DToImage=function(t){var e=(0,o.default)(t.shape,2),n=e[0],r=e[1],i=t.dataSync(),a=document.createElement("canvas");a.width=r,a.height=n;for(var s=a.getContext("2d"),u=s.getImageData(0,0,a.width,a.height),c=0;c2&&void 0!==arguments[2]?arguments[2]:function(){},r=t,i=document.createElement("video");return r.onplay=function(){var t=r.captureStream();i.srcObject=t,i.width=e,i.height=e,i.autoplay=!0,i.playsinline=!0,i.muted=!0,n()},i},e.cropImage=c,e.imgToTensor=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return a.tidy(function(){var n=a.browser.fromPixels(t);return e&&(n=a.image.resizeBilinear(n,e)),c(n).expandDims(0).toFloat().div(a.scalar(127)).sub(a.scalar(1))})},e.isInstanceOfSupportedElement=function(t){return t instanceof HTMLVideoElement||t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof ImageData},e.flipImage=function(t){var e,n,r;if(r=t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData?t:"object"===(void 0===t?"undefined":(0,i.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLCanvasElement||t.elt instanceof HTMLVideoElement||t.elt instanceof ImageData)?t.elt:"object"===(void 0===t?"undefined":(0,i.default)(t))&&t.canvas instanceof HTMLCanvasElement?t.canvas:t,HTMLVideoElement,e=r.width,n=r.height,s.default.checkP5()){var o=s.default.p5Instance.createGraphics(e,n);return o.push(),o.translate(e,0),o.scale(-1,1),o.image(t,0,0,e,n),o.pop(),o}var a=document.createElement("canvas");a.width=e,a.height=n;var u=a.getContext("2d");return u.drawImage(r,0,0,e,n),u.translate(e,0),u.scale(-1,1),u.drawImage(a,-1*e,0,e,n),a},e.imgToPixelArray=function(t){var e,n,o;o=t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData?t:"object"===(void 0===t?"undefined":(0,i.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLCanvasElement||t.elt instanceof HTMLVideoElement||t.elt instanceof ImageData)?t.elt:"object"===(void 0===t?"undefined":(0,i.default)(t))&&t.canvas instanceof HTMLCanvasElement?t.canvas:t,HTMLVideoElement,e=o.width,n=o.height;var a=document.createElement("canvas");a.width=e,a.height=n;var s=a.getContext("2d");s.drawImage(o,0,0,e,n);var u=s.getImageData(0,0,e,n);return(0,r.default)(u.data)}},function(t,e){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},function(t,e,n){var r=n(127);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(372),i=n(3),o=n(167)("metadata"),a=o.store||(o.store=new(n(369))),s=function(t,e,n){var i=a.get(t);if(!i){if(!n)return;a.set(t,i=new r)}var o=i.get(e);if(!o){if(!n)return;i.set(e,o=new r)}return o};t.exports={store:a,map:s,has:function(t,e,n){var r=s(e,n,!1);return void 0!==r&&r.has(t)},get:function(t,e,n){var r=s(e,n,!1);return void 0===r?void 0:r.get(t)},set:function(t,e,n,r){s(n,r,!0).set(t,e)},keys:function(t,e){var n=s(t,e,!1),r=[];return n&&n.forEach(function(t,e){r.push(e)}),r},key:function(t){return void 0===t||"symbol"==typeof t?t:String(t)},exp:function(t){i(i.S,"Reflect",t)}}},function(t,e,n){"use strict";if(n(22)){var r=n(70),i=n(8),o=n(13),a=n(3),s=n(156),u=n(227),c=n(50),l=n(81),f=n(88),d=n(35),h=n(79),p=n(48),m=n(16),g=n(367),v=n(85),b=n(60),y=n(42),w=n(105),x=n(14),_=n(25),k=n(238),S=n(84),E=n(39),O=n(83).f,A=n(236),C=n(87),M=n(15),N=n(57),T=n(166),I=n(128),D=n(233),j=n(103),R=n(161),F=n(82),P=n(234),z=n(378),L=n(21),B=n(40),U=L.f,W=B.f,q=i.RangeError,V=i.TypeError,H=i.Uint8Array,$=Array.prototype,G=u.ArrayBuffer,K=u.DataView,X=N(0),Y=N(2),J=N(3),Z=N(4),Q=N(5),tt=N(6),et=T(!0),nt=T(!1),rt=D.values,it=D.keys,ot=D.entries,at=$.lastIndexOf,st=$.reduce,ut=$.reduceRight,ct=$.join,lt=$.sort,ft=$.slice,dt=$.toString,ht=$.toLocaleString,pt=M("iterator"),mt=M("toStringTag"),gt=C("typed_constructor"),vt=C("def_constructor"),bt=s.CONSTR,yt=s.TYPED,wt=s.VIEW,xt=N(1,function(t,e){return Ot(I(t,t[vt]),e)}),_t=o(function(){return 1===new H(new Uint16Array([1]).buffer)[0]}),kt=!!H&&!!H.prototype.set&&o(function(){new H(1).set({})}),St=function(t,e){var n=p(t);if(n<0||n%e)throw q("Wrong offset!");return n},Et=function(t){if(x(t)&&yt in t)return t;throw V(t+" is not a typed array!")},Ot=function(t,e){if(!(x(t)&> in t))throw V("It is not a typed array constructor!");return new t(e)},At=function(t,e){return Ct(I(t,t[vt]),e)},Ct=function(t,e){for(var n=0,r=e.length,i=Ot(t,r);r>n;)i[n]=e[n++];return i},Mt=function(t,e,n){U(t,e,{get:function(){return this._d[n]}})},Nt=function(t){var e,n,r,i,o,a,s=_(t),u=arguments.length,l=u>1?arguments[1]:void 0,f=void 0!==l,d=A(s);if(void 0!=d&&!k(d)){for(a=d.call(s),r=[],e=0;!(o=a.next()).done;e++)r.push(o.value);s=r}for(f&&u>2&&(l=c(l,arguments[2],2)),e=0,n=m(s.length),i=Ot(this,n);n>e;e++)i[e]=f?l(s[e],e):s[e];return i},Tt=function(){for(var t=0,e=arguments.length,n=Ot(this,e);e>t;)n[t]=arguments[t++];return n},It=!!H&&o(function(){ht.call(new H(1))}),Dt=function(){return ht.apply(It?ft.call(Et(this)):Et(this),arguments)},jt={copyWithin:function(t,e){return z.call(Et(this),t,e,arguments.length>2?arguments[2]:void 0)},every:function(t){return Z(Et(this),t,arguments.length>1?arguments[1]:void 0)},fill:function(t){return P.apply(Et(this),arguments)},filter:function(t){return At(this,Y(Et(this),t,arguments.length>1?arguments[1]:void 0))},find:function(t){return Q(Et(this),t,arguments.length>1?arguments[1]:void 0)},findIndex:function(t){return tt(Et(this),t,arguments.length>1?arguments[1]:void 0)},forEach:function(t){X(Et(this),t,arguments.length>1?arguments[1]:void 0)},indexOf:function(t){return nt(Et(this),t,arguments.length>1?arguments[1]:void 0)},includes:function(t){return et(Et(this),t,arguments.length>1?arguments[1]:void 0)},join:function(t){return ct.apply(Et(this),arguments)},lastIndexOf:function(t){return at.apply(Et(this),arguments)},map:function(t){return xt(Et(this),t,arguments.length>1?arguments[1]:void 0)},reduce:function(t){return st.apply(Et(this),arguments)},reduceRight:function(t){return ut.apply(Et(this),arguments)},reverse:function(){for(var t,e=Et(this).length,n=Math.floor(e/2),r=0;r1?arguments[1]:void 0)},sort:function(t){return lt.call(Et(this),t)},subarray:function(t,e){var n=Et(this),r=n.length,i=v(t,r);return new(I(n,n[vt]))(n.buffer,n.byteOffset+i*n.BYTES_PER_ELEMENT,m((void 0===e?r:v(e,r))-i))}},Rt=function(t,e){return At(this,ft.call(Et(this),t,e))},Ft=function(t){Et(this);var e=St(arguments[1],1),n=this.length,r=_(t),i=m(r.length),o=0;if(i+e>n)throw q("Wrong length!");for(;o255?255:255&r),i.v[h](n*e+i.o,r,_t)}(this,n,t)},enumerable:!0})};y?(p=n(function(t,n,r,i){l(t,p,c,"_d");var o,a,s,u,f=0,h=0;if(x(n)){if(!(n instanceof G||"ArrayBuffer"==(u=w(n))||"SharedArrayBuffer"==u))return yt in n?Ct(p,n):Nt.call(p,n);o=n,h=St(r,e);var v=n.byteLength;if(void 0===i){if(v%e)throw q("Wrong length!");if((a=v-h)<0)throw q("Wrong length!")}else if((a=m(i)*e)+h>v)throw q("Wrong length!");s=a/e}else s=g(n),o=new G(a=s*e);for(d(t,"_d",{b:o,o:h,l:a,e:s,v:new K(o)});fy;y++)if((g=e?b(a(p=t[y])[0],p[1]):b(t[y]))===c||g===l)return g}else for(m=v.call(t);!(p=m.next()).done;)if((g=i(m,b,p.value,e))===c||g===l)return g}).BREAK=c,e.RETURN=l},function(t,e){t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){"use strict";var r=n(8),i=n(21),o=n(22),a=n(15)("species");t.exports=function(t){var e=r[t];o&&e&&!e[a]&&i.f(e,a,{configurable:!0,get:function(){return this}})}},function(t,e,n){var r=n(393),i=n(250).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},function(t,e,n){var r=n(5),i=n(392),o=n(250),a=n(251)("IE_PROTO"),s=function(){},u=function(){var t,e=n(253)("iframe"),r=o.length;for(e.style.display="none",n(249).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("